home *** CD-ROM | disk | FTP | other *** search
/ LSD Docs / LSD Docs.iso / FILEZ / lsd28.dms / lsd28.adf / AmigaCBeginners.1.DOC.pp / AmigaCBeginners.1.DOC
Text File  |  1990-09-07  |  212KB  |  5,619 lines

  1. --------------------------------------------------------------------------
  2. *                                                                        *
  3. *                       AMIGA 'C' FOR BEGINNERS                          *
  4. *                                                                        *
  5. * TYPED IN BY RAZOR BLADE OF ALLIANCE                                    *
  6. *                                                                        *
  7. * GREETS TO :-  VIPER , BLACKBEARD , ARAMIS , CHAOS , MIT ,              *
  8. *               SHADOWFAX AND ALCHEMIST.                                 *
  9. *                                                                        *
  10. *-------------------------------------------------------------------------
  11.  
  12.  
  13. NOTE ** :-  DON'T WORRY ABOUT THE MISSING PAGE NUMBERS. THERE ARE A LOT A
  14.             BLANK PAGES IN THE ORIGINAL BOOK AND THE TITLE OF EACH CHAPTER
  15.             IS PRINTED IN LARGE CHARATERS ON A WHOLE PAGE. THERE WILL 
  16.             THEREFORE USUALLY BE TWO OR THREE PAGE NUMBERS MISSING BETWEEN 
  17.             EACH CHAPTER (RIP-OFF OR WHAT !!!).
  18.  
  19.  
  20.             The notation ** has been used to represent exponentiation.
  21.             I.e 10 squared woudl be shown as 10**2.
  22.                            TABLE OF CONTENTS.
  23.  
  24. 1.  Introduction to C ...................... 1
  25. 1.1   Program Execution .................... 4
  26. 1.2   Compiler Vs Interpreter .............. 5
  27.  
  28. 2   Beginning C ............................ 7
  29. 2.1   The Editor ........................... 10
  30. 2.2   The Compiler ......................... 11
  31. 2.3   The Linker ........................... 12
  32. 2.4   Putting it all together .............. 13
  33.  
  34. 3.  The First Program ...................... 15
  35. 3.1   Using ED ............................. 18
  36. 3.2   Compiling ............................ 19
  37. 3.3   Error Messages ....................... 21
  38.  
  39. 4.  Theory and Practise .................... 23
  40. 4.1   Program Format ....................... 27
  41. 4.2   Defining a Function .................. 28
  42. 4.3   PRINTF and Escape Sequences .......... 29
  43. 4.4   Comments ............................. 30
  44. 4.5   Varaibles and Arithmetic ............. 31
  45. 4.5.1   Integers ........................... 31
  46. 4.5.2   The IF statement ................... 32
  47. 4.5.3   Calculating with C ................. 35
  48. 4.5.4   Floating Point Numbers ............. 37
  49. 4.5.5   Characters and Character Strings ... 39    
  50.  
  51. 5.  Loops .................................. 43
  52. 5.1   WHILE Loops .......................... 45
  53. 5.2   FOR Loops ............................ 48
  54. 5.3   DO...WHILE Loop ...................... 49
  55. 5.3.1   More Error Checking ................ 49
  56. 5.4   AND and OR ........................... 52
  57.  
  58. 6.  Strings ................................ 55
  59. 6.1   Backtracking ......................... 57
  60.  
  61. 7.  Calculating in C ....................... 59
  62.  
  63. 8.  Variables .............................. 63
  64. 8.1   Variable Names ....................... 65
  65. 8.2   Data Types ........................... 67
  66. 8.3   Type Conversion ...................... 70
  67. 8.4   The Cast Operation ................... 71
  68.  
  69. 9.  PRINT and SCANF ........................ 73
  70. 9.1   More escape sequences................. 75
  71. 9.2   Format Specification ................. 77
  72. 9.3   Octal and Hexadecimal ................ 80
  73. 9.3.1   Conversion Program ................. 82
  74. 9.4   Character codes ...................... 84
  75. 9.4.1   About the backslash ................ 85
  76. 9.4.2   Going the other Direction .......... 86
  77.  
  78. 10. The Pre-processor ...................... 87
  79. 10.1  #define .............................. 89
  80. 10.2  #include ............................. 91
  81.  
  82. 11. Abbreviations .......................... 93
  83. 11.1  Increment and Decrement .............. 97
  84. 11.2  Definition, Declaration, Initialising. 99
  85. 11.3  Multiple Assignments in C ........... 101
  86.  
  87. 12. Functions ............................. 103
  88. 12.1  Functions with Arguments ............ 106
  89. 12.2  Functions without return values ..... 108
  90. 12.3  Other Functions ..................... 109
  91. 12.3.1  STRCPY - Version 1 ................ 109
  92. 12.3.2  STRLEN ............................ 111
  93.  
  94. 13. Arrays ................................ 113
  95. 13.1  Multi-dimensional Arrays ............ 116
  96.  
  97. 14. More about loops ...................... 121
  98. 14.1  More about the FOR loop ............. 123
  99. 14.2  BREAK ............................... 124
  100. 14.3  CONTINUE ............................ 125
  101. 14.4  The SWITCH directive ................ 126
  102.  
  103. 15. Pointers and Addresses ................ 129
  104. 15.1  Addresses............................ 131
  105. 15.2  Pointers ............................ 133
  106. 15.2.1  The EXCHANGE function with pointer. 134
  107. 15.2.2  STRCPY - version 2 ................ 135
  108. 15.2.3  STRCPY - version 3 ................ 135
  109. 15.3  Pointer without storage ............. 138
  110.  
  111. 16. Storage Classes ....................... 141
  112. 16.1  Auto ................................ 143
  113. 16.2  Static .............................. 144
  114. 16.3  External ............................ 145
  115. 16.4  Register ............................ 146
  116. 16.4.1  Fast STRCPY routine ............... 147
  117. 16.5  Local ............................... 149
  118.  
  119. 17. User defined Libraries ................ 151
  120. 17.1  The STRCMP function ................. 154
  121. 17.2  ITOA ................................ 157
  122. 17.3  Reverse ............................. 159
  123.  
  124. 18. C features ............................ 161
  125. 18.1  The ?: Operator ..................... 163
  126. 18.2  The SIZEOF function ................. 164
  127. 18.3  Bit manipulation .................... 165
  128. 18.3.1  AND ............................... 165
  129. 18.3.2  OR ................................ 166
  130. 18.3.3  Bitwise Shift Operators ........... 167
  131. 18.3.4  EXCLUSIVE OR ...................... 168
  132. 18.3.5  One's Complement .................. 168
  133. 18.4  GOTO ................................ 169
  134.  
  135. 19. Complex Data Types .................... 171
  136. 19.1  STRUCT .............................. 173
  137. 19.2  Bit fields .......................... 175
  138. 19.3  Unions .............................. 176
  139. 19.4  ENUM ................................ 177
  140. 19.5  TYPEDEF ............................. 178
  141.  
  142. 20. Important Concepts .................... 179
  143. 20.1  Declarations ........................ 181
  144. 20.2  Initialisation ...................... 184
  145.  
  146. 21. Pointer Arrays ........................ 187
  147.  
  148. 22. Useful Macros ......................... 193
  149. 22.1  Macro Error Sources ................. 196
  150. 22.2  Library Macros ...................... 198
  151.  
  152. 23. Communication ......................... 201
  153. 23.1  Passing data with CLI ............... 203
  154. 23.2  Buffered Input / Output ............. 206
  155. 23.3  More buffered Input / Output ........ 211
  156. 23.4  Unbuffered Input / Output ........... 213
  157. 23.5  Direct Access ....................... 216
  158. 23.6  Reading a Character ................. 218
  159. 23.6.1  Standard Input / Output ........... 218
  160. 23.7  A User Window ....................... 219
  161. 23.7.1  The Three Windows ................. 219
  162. 23.8  Redirection ......................... 222
  163.  
  164. 24. Tricks and Tips ....................... 225
  165. 24.1  Starting from the Workbench ......... 227
  166. 24.2  Other Preprocessor Directives ....... 229
  167. 24.3  Finding and Removing Errors ......... 231
  168.  
  169. 25. System Programming .................... 233
  170. 25.1  The Intuition Principle ............. 235
  171. 25.2  A Window under Intuition ............ 236
  172. 25.2.1  The Window Flags .................. 237
  173. 25.2.2  Opening a Window .................. 238
  174. 25.2.3  A window program .................. 239
  175. 25.3  Screens ............................. 242
  176. 25.3.1  A Screen program .................. 243
  177. 25.4  Text / Grpahic Window Display ....... 246
  178. 25.4.1  TEXT .............................. 246
  179. 25.4.2  MOVE .............................. 246
  180. 25.4.3  DRAW .............................. 247
  181. 25.4.4  Small Drawing Program ............. 248
  182. 25.4.5  Low Resolution and Interlace Modes. 252
  183. 25.4.6  Pixel Processing .................. 253
  184. 25.5  DOS ................................. 257
  185. 25.6  SETCOMMENT .......................... 258
  186. 25.7  Read Directory ...................... 259
  187. 25.8  Conclusion .......................... 262
  188.  
  189. Appendices ................................ 263
  190.  
  191. A.  Functions ............................. 265
  192. B.  The History of C ...................... 270
  193. C.  The Lattice C Compiler ................ 272
  194. D.  The Aztec C Compiler .................. 273
  195. E.  Reserved C Words ...................... 276
  196. F.  Operator Precedence ................... 277
  197. G.  Storage Classes ....................... 278
  198. H.  Type Conversions ...................... 278
  199. I.  Modes for FOPEN ....................... 279
  200.  
  201. Index ..................................... 281
  202.  
  203. ==========================================================================
  204.  
  205.                 CHAPTER 1 - INTRODUCTION TO C
  206.  
  207. So you want to learn C. That's obvious or you wouldn't be reading this
  208. book. The goal of this book is to help you learn to program in C on the
  209. Amiga in as little time as possible. AMIGA C FOR BEGINNERS is written as a
  210. short course in the C language for anyone who wants to learn about the C
  211. language from scratch, without a lot of technical jargon.
  212.  
  213. This book is divided roughly into two parts. The first part introduces the
  214. reader to the basic structures of C programming through operating the
  215. editor, compiler and linker. It also contains many sample programs. You'll
  216. be able to write your own short programs in C in only a few hours.
  217.  
  218. This first part also takes the beginning C programmer through the
  219. essentials of C - calculations, string handling, loops and more. It even
  220. helps you find the errors made most often by most new C programmers.
  221.  
  222. The second part, which begins at chapter 10, explains the background and
  223. peculiarities of each C statement and function. These include preprocessor
  224. commands, arrays, loops, pointers, addresses and memory classes. If these
  225. words don't mean anything to you now, they will when you start reaidng the
  226. second section.
  227.  
  228. The second part also discusses macros, interfacing your Amiga to the
  229. outside world, tricks and tips for the C language and graphic programming.
  230.  
  231. The appendices describe the history and development of the C language, as
  232. well as operating instructions for a number of popular C compilers (see
  233. your compiler's instruction manual since many compilers are constantly
  234. being upgraded). In addition, you'll find a number of practical C
  235. functions, mathematical precedence, reserved C keywords, memory classses
  236. and type conversions.
  237.  
  238. This chapter described the general nature of C. You'll see it's advantages
  239. and disadvantages compared to interpreted languages, as well as advantages
  240. and disadvantages compared to other compiler languages. You'll also see why
  241. C stands out above so many other computer languages.
  242.  
  243.                                 PAGE 3
  244.  
  245. --------------------------------------------------------------------------
  246.  
  247. 1.1 PROGRAM EXECUTION.
  248.  
  249. Before starting we need to ask the big question WHAT IS C?
  250.  
  251. There are two kinds of computer languages. First, there are interpreted
  252. languages such as BASIC and LOGO. Second there are compiled languages such
  253. as C, Pascal or Modula 2. Section 1.2 contains detailed information about
  254. the advantages and disadvantages of interpreters and compilers.
  255.  
  256. Compilers are programs which translate the language statements into a form
  257. understandable to the computer. This form consists of the numbers 0 and 1
  258. (the numbers used in the binary system). Since people can't remember long
  259. strings of zeros and ones, the computer can be told to interprete words and
  260. other number systems as binary numbers. For example, a typical machine
  261. language instruction LDA means "Load the Accumulator", which is easier to
  262. remember than the binary number 10011101.
  263.  
  264. The computer must contain a Central Processing Unit (CPU) to respond to the
  265. machine language instruction available in response to every keyword.
  266. Programming with the binary machines is called machine language
  267. programming. Using machine language mnemonics or intructions is called
  268. assembly language. The instruction which executes on one computer may not
  269. even exist on another computer.
  270.  
  271. It would be easier for the programmer if the computer could be told in
  272. plain English what to do. Needless to say, computer languages haven't
  273. reached the level of a DWIM (Do What I Mean) interface. This type of
  274. language may exist a few years from now, when technology produces more
  275. helpful developments using artificial intelligence.
  276.  
  277. High level languages act as a compromise between machine language and the
  278. human language. These languages contain a limited number of statements or
  279. keywords which in turn execute specific tasks. Unlike assembly language,
  280. many of these languages aren't tailored to a specific computer. The
  281. computer must execute several hundred machine instructions for every single
  282. statement in the high level language. An example would be the basic command
  283. "Load filename", which tells the computer to load a file.
  284.  
  285.                                 PAGE 4
  286.  
  287. --------------------------------------------------------------------------
  288.  
  289. 1.2 COMPILER VS INTERPRETER.
  290.  
  291. As previously mentioned, two types of higher level languages exist:
  292. interpreted and compiled. An interpreter searches for keywords in the
  293. program text (or source), verifies that the command is a legal one and
  294. executes the equivalent machine language instructions. Then the interpreter
  295. searches for the next command, tests it and executes the machine
  296. instruction etc..
  297.  
  298. This translation process performed by the interpreter can be compared to
  299. the work of a human foreign language interpreter. An interpreter is a
  300. translator which translates the words of the higher level language into
  301. machine level instructions as needed.
  302.  
  303.  
  304. A compiler translates the source program ONCE into executable form. This is
  305. similar to someone who translates foreign language literature into his/her
  306. own language. This translator takes the time to select the proper choice of
  307. words for the text, unlike the interpreter who mediates a conversation
  308. between two people from different language backgrounds.
  309.  
  310. The interpreter executes programs immediately. The interpreter can also be
  311. stopped by the user to check on certain values stores in certain variables.
  312. Interpreted program execution can usually be continued without causing
  313. problems. The main advantages of interpreters are flexibility and
  314. spontaneity.
  315.  
  316. The compiler translates the program source only once. The compiler may
  317. spend a few minutes compiling the program before it can be executed.
  318. Afterwards, the compiled program executes much faster than an interpreted
  319. program, since the compiler doesn't have to re-translate the source
  320. program. This advantage become most evident in program loops in which a
  321. command can be executed several thousand times. The interpreter translates
  322. the command into machine language, repeating this process a few thousand
  323. times. The compiled program already knows what to do without repeating the
  324. translation. The advantages of compiled languages lie in shorter execution
  325. times for compiled programs.
  326.  
  327. Interpreters, because of easy access to their programs, let the programmer
  328. enter corrections and modifications on the fly. They also let the
  329. programmer enter and execute program code until an error occurs. This
  330. "run-until-it-breaks-then-fix-it" attitude causes lazy, unstructured
  331. programming style.
  332.  
  333.                                 PAGE 5
  334.  
  335. --------------------------------------------------------------------------
  336.  
  337.  
  338. Compilers don't usually allow easy error correction. When an error occurs
  339. you must re-load the program source editor, fix the errors in the source
  340. code and recompile the program. In addition, compiled languages require a
  341. specific language structure, or the program won't compile. The source code
  342. must be correct from beginning to end or the compiler will not compile it.
  343.  
  344. The biggest advantages that C has over other languages is it's
  345. transportability. This means that you should be able to take a C source
  346. code from an Amiga, transfer it to a PC, make changes to fit the PC's File
  347. handling and other machine-specific tasks, and compile the C  source code
  348. on the PC with no problem.
  349.  
  350. There you have a general overview of the advantages and disadvantages of
  351. compiled languages and interpreted languages. The next chapter spends some
  352. time talking about these languages as well, while adding specifics about
  353. the subject of the book - the C language.
  354.  
  355.                                 PAGE 6
  356.  
  357. ==========================================================================
  358.  
  359.                            CHAPTER 2 - BEGINNING C
  360.                                 
  361.  
  362. Let's take a look at the process involved in developing a C program.
  363. Although it may seem long and involved, don't panic. Once you learn the
  364. basics of developing a high-level language program it get's easier.
  365.  
  366. One word of warning: Don't skip this chapter, even if you have previous
  367. experience with C. You might learn something you didn't know before about
  368. the language.
  369.  
  370. Programs begin with an idea. The user has a task that he wants to
  371. accomplish using a program - and the program should perform the task
  372. easier, faster and more accurately than a human could do it. This idea
  373. could be for a drawing program; a spreadsheet for calculating payroll and
  374. figures; a fast disk copier; or just a simple text display on the screen.
  375.  
  376. Once the general idea is developed, it helps if the programmer sits down
  377. and writes out the goals of the idea, and how the program can do this. This
  378. writing stage can be in plain English, since it should be as readable for
  379. you as possible. This written documentation of the program execution is
  380. sometimes called pseudo-code, since it tells what the program should do
  381. without actually writing which statements the program needs to perform the
  382. task. When writing the pseudo-code this program, keep it broken down into
  383. smaller modules whenever possible.
  384.  
  385. A data flowchart and program flowchart should be developed from the written
  386. documentation of the idea, just as in any other computer language. After it
  387. has been determined how the program flow should appear, the user can
  388. proceed to the computer to program the idea.
  389.  
  390. The C language uses three different programs which work together in
  391. generating programs;
  392.  
  393.         .   The EDITOR, in which the user enteres and corrects the 
  394.             source program.
  395.  
  396.         .   The COMPILER, which compiles the program.
  397.  
  398.         .   The LINKER, which joins the main program with other compiled 
  399.             programs and functions to make a fully executable program.
  400.  
  401. The rest of this chapter dicusses the use of each program in the
  402. development of C programs.
  403.  
  404.                                 PAGE 9
  405.  
  406. --------------------------------------------------------------------------
  407.  
  408. 2.1  THE EDITOR
  409.  
  410. You need some sort of text editor to enter a C program from the keyboard.
  411. An editor is nothing more than a simple word processor. It usually only
  412. contains minimal text processing capabilities. The program only usually
  413. allows you to type in, load, save and edit the text of the source code:
  414. Nothing fancy like block functions or save and replace capabilities.
  415.  
  416. Most word processor programs can be used for typing in the text of a C
  417. program. If you use a word processor, you may not enter any special control
  418. characters (e.g. bold fonts and text formatting) because the C compiler
  419. would not recognise them. Many word processors provide the option of
  420. letting you save a file as an ASCII file.
  421.  
  422. If you use a word processor as an editor, it must allow you to enter the
  423. special control characters needed by C source codes. C programd use braces
  424. ({}), brackets ([]), the backslash (\), the number sign (#), the pipe
  425. character (|) and the tilde character (~).
  426.  
  427. Maybe you can't afford a word processor, or maybe your word processor
  428. doesn't have the necessary characters. The workbench disk which comes with
  429. your Amiga contains an editor named ED. Ed is a basic text editor, which
  430. you can find on the workbench disk of the Amiga from the CLI. Invoke the
  431. editor by entering the CLI, typing ED and the name of the file you want to
  432. load/edit, and press the <Return> key.
  433.  
  434. The editor is loaded and then the C program is typed in. This text, called
  435. the C source code, is stored on the disk under a filename. The
  436. characteristics that set this apart from normal word processing files
  437. appears in the file entension: C source codes must contain a file extension
  438. of .c. Examples of names can be SORT.c or ARCHIVE.c; note that these names
  439. indicate the contents of each file. Try to use meaningful names like this
  440. instead of cryptic names like a.c or this.c. The extension of .C is
  441. especially important, since several files with the same name but different
  442. extensions are generated by a C compiler. After a file is created and
  443. saved, you can then call the C compiler to compile the C source code.
  444.  
  445.                                 PAGE 10
  446.  
  447. --------------------------------------------------------------------------
  448.  
  449. 2.2  THE COMPILER
  450.  
  451. Calling the compiler loads the C compiler into memory. The compiler reads
  452. the source code and begins to convert the C source code into compiled
  453. machine language. Most compilers read the source code twice (two pass
  454. compiler). During the first pass, if it encounters an invalid expression or
  455. keyword, it stops compiling and displays an error message on the screen or
  456. writes the error to a disk message file.
  457.  
  458. Whenever an error is found, you must reload the editor, and correct the
  459. source code. Once you've fixed the errors, you must save the source code
  460. file, exit the editor and restart the compiler. If the compiler finds
  461. errors again, you must repeat the above procedures.
  462.  
  463. Before going any farther, you should realise one thing. Writing the C
  464. source code requires proper preparation. If you just enter the source code
  465. without giving any thought to what you're typing in, you'll spend more time
  466. learning about error messages and the editor than you will spend learning
  467. about the C language. In the beginning, prepare to see plenty of errors,
  468. and be patient with yourself as you go from compiler to editor to compiler.
  469.  
  470. When you've corrected all of the errors in the source code, the compiler
  471. can finish the first pass without stopping and performs the second pass.
  472. This second pass does the final transformation into OBJECT (compiled) code,
  473. The compiler saves the object code to disk under the same name as the
  474. source code, but with an extension of .O. For example, a source code named
  475. source.c generates an object file names source.o. The object file needs one
  476. more step before it can become executable program code- this is the linker.
  477.  
  478.                                 PAGE 11
  479.  
  480. --------------------------------------------------------------------------
  481.  
  482. 2.3 THE LINKER.
  483.  
  484. We're not quite done yet. The object file must still be run through the
  485. linker. The linker searches for all functions used by the program from the
  486. C libraries, and links the necessary functions into one program.
  487.  
  488. A function is a subroutine similar to a procedure in Pascal. Functions are
  489. capable of solving small tasks such as drawing a line or displaying a
  490. character on the screen. The libraries contained in most C compiler
  491. packages include frequently used functions stored in object (compiled)
  492. form. These functions could be input/output functions, graphic routines,
  493. sound routines or even trigonometric functions.
  494.  
  495. The linker identifies the functions required for a complete program and
  496. adds them to the main program. This saves a programmer a lot of work. The
  497. functions simply require the passing of values instead of retyping the
  498. source code for each function from scratch.
  499.  
  500. The C linker permits the development of large programs in modular form.
  501. This means the several parts can be (and often are) developed separately.
  502. The uer can compile and test every module separately. This has the
  503. advantage that the complete C program doesn't have to be reloaded anfd
  504. recompiled every time the compiler detects an error. The linker eventually
  505. links all the compiled modules into one complete, executable C program.
  506.  
  507. The linker cannot handle non-compiled source code. It can only link
  508. compiled functions together. Source code can load other source codes during
  509. compilation, but we'll see more on this later.
  510.  
  511.                                 PAGE 12
  512.  
  513. --------------------------------------------------------------------------
  514.  
  515. 2.4 PUTTING IT ALL TOGETHER.
  516.  
  517. The Amiga's CLI (command line interface) is used to specifiy the parameters
  518. for the editor, the C compiler and the C linker. For example, entering the
  519. following line in CLI calls the Lattice C linker;
  520.  
  521.         ALINK file1.o file2.o TO complete
  522.  
  523. You already know that a program may have to be compilerd several times
  524. before it is free of errors (syntax errors, not logical errors). You must
  525. enter the above line exactly as written. Entering the line incorrectly can
  526. cause errors in itself. The developers of most C compilers took this into
  527. consideration, and added a special feature to allow easy linker access from
  528. text files.
  529.  
  530. THE MAKE FILE.
  531.  
  532. The inputs required to compile and link a C source code can be written to a
  533. file called a MAKE file. This MAKE file calls all the necessary programs
  534. such as the compiler or linker. The C system reads the file just as if the
  535. user had input the text direct from the keyboard.
  536.  
  537. It's easy to create a MAKE file. Instead of executing, the C compiler calls
  538. directly. You invoke the editor and write the calls to a script file. Once
  539. you save this file to disk you now have a MAKE file.
  540.  
  541. AmigaDOS' EXECUTE command reads this file and passes the infornation to the
  542. C compiler sections needed to make the final executable program. See
  543. Appendix C for one example of a MAKE file and it's contents.
  544.  
  545.                                 PAGE 13
  546.  
  547. ==========================================================================
  548.  
  549.                         CHAPTER 3 - THE FIRST PROGRAM.
  550.  
  551. The following code is our first C language program. Don't enter it yet -
  552. you'll type it in a few minutes starting at section 3.1. Here's the source
  553. code so you can see what it looks like:
  554.  
  555.         #include <stdio.h>
  556.         void main()
  557.         {
  558.           printf("Hello, I am here!");
  559.         }
  560.  
  561. To see what the program produces, the text must be entered using an editor.
  562. When you use the editor please enter the text exactly as it is printed here
  563. and in section 3.1. This avoids error message which will cause problems
  564. Once you've become comfortable working in C, you can change programs around
  565. to suit your own needs. But don't change anything here until after the
  566. program compiles and links exactly as you see here.
  567.  
  568. A step by step procedure follows. If you're on the workbench you must start
  569. the CLI before anything else. The CLI can be found in the system drawer
  570. located on the workbench disk. Workbench 1.3 users can use the shell
  571. program which is an enhanced version of CLI.
  572.  
  573. Workbench 1.2 users who can't find the CLI may have it switched off with
  574. the settings in preferences 1.2. Using preferences 1.2 you must click on
  575. the ON gadget next to the word CLI. Once you close and reopen the workbench
  576. disk icon, the CLI should appear in the window.
  577.  
  578. After you invoke the CLI or shell a new window appears. This window prompts
  579. for an input with the message:
  580.  
  581.                 1>
  582.  
  583. For a super computer such as the Amiga this program is something unusual.
  584. No icons appear, the mouse can only be used to move and size the window,
  585. and the CLI only accepts input from the keyboard. Use the mouse to enlarge
  586. the CLI window to it's maximum size. Everything that occurs from now on
  587. will be displayed on the CLI window. Now put the mouse aside - you won't be
  588. needing it for a while.
  589.  
  590.                                 PAGE 17
  591.  
  592. --------------------------------------------------------------------------
  593.  
  594. 3.1 USING ED.
  595.  
  596. First you'll need an editor to enter the program. The Ed editor can be
  597. called from the C: directory on your Workbench disk. The following executes
  598. ED and creates a new file named HELLO.C:
  599.  
  600.                 1> ED HELLO.C
  601.  
  602. The computer places the 1> prompt at the beginning of the line. Some
  603. versions of CLI may also display the current directory (e.g. The shell from
  604. workbench 1.3).
  605.  
  606. The name HELLO.C will be the name of our first C language program. It
  607. doesn't matter whether you type the name in upper case or lower case
  608. characters.
  609.  
  610. If you made a typing error, press the <backspace> key to delete the last
  611. character typed. The <backspace> key has an arrow pointing to the left on
  612. some versions of the Amiga. If you prefer you can press the <Ctrl> <x> key
  613. combination to delete the entire line of text.
  614.  
  615. Press the <Return> key to execute the command and invoke the editor.  A
  616. window appears and displays the text "Creating new file". The user now
  617. enters the program. The editor allows you to move the cursor around the
  618. file using the cursor keys to make corrections and changes. Type the
  619. following text:
  620.  
  621.         #include<stdio.h>
  622.         void main()
  623.         {
  624.            printf("Hello, I am Here!");
  625.         }
  626.  
  627. Once you've finished typing the text, press the <esc> key, then press the
  628. <S> and <A> keys. Pressing the <return> key saves the text (this
  629. combination will be called <ESC><SA> from here on). Press 
  630. <ESC><X><RETURN> to save the text and quit the editor. The system returns
  631. you to the CLI. Pressing <ESC><Q> returns you to the CLI without saving the
  632. file. See book AMIGADOS INSIDE AND OUT from Abacus for more information
  633. about ED.
  634.  
  635. Pressing <ESC><X><RETURN> returns the user to the CLI window immediately.
  636. You now have your first C source code ready to compile.
  637.  
  638.                                 PAGE 18
  639.  
  640. --------------------------------------------------------------------------
  641.  
  642. 3.2  COMPILING
  643.  
  644. LATTICE 4.0
  645.  
  646. Start the Lattice 4.0 compiler with the following:
  647.  
  648.         1> lc -L hello
  649.  
  650. For Lattice C 4.0, the following should now appear on the screen. Your
  651. screen may differ slighly. If you get error messages see section 3.3
  652.  
  653. ......................................................................
  654.  
  655. 1> lc -L hello
  656. Lattice Amiga Dos C Compiler Version 4.0
  657. Copyright (c) 1987 SAS Institute Inc. All rights reserved.
  658.  
  659. Compiling Hello.c
  660. Module Size P=00000014  D=00000012  U=00000000
  661. Total Files: 1,  Compiled OK: 1
  662.  
  663. Linking Hello
  664. BLink - Version 7.2
  665. Copyright (C) 1986 The Software Distillery.
  666. Copyright (C) 1987 SAS Institute Inc. All rights reserved.
  667. Box 8000 SAS Circle, Cary NC 27511-8000 - Telex 802505 (919) 467-8000
  668.  
  669.  
  670.  
  671. Blink Complete - Maximum code size = 5488 ($00001570) bytes.
  672.  
  673. Final Output file size = 5312 (000014c0) bytes.
  674. 1>
  675.  
  676. ......................................................................
  677.  
  678. AZTEC C
  679.  
  680. To compile the program using the Aztec C  compiler requires two steps. The
  681. Aztec system first compiles the source code then assembles  and links it. A
  682. MAKE file can be quite useful. Enter the following for the Aztec C
  683. compiler:
  684.  
  685.         1> cc +L hello
  686.  
  687. The above sequence may not function in some cases. If not enter the same
  688. line but omit the +L. Aztec C should display the following on the screen.
  689. Your screen may differ slightly. If you get error message see section 3.3
  690.  
  691. ......................................................................
  692.  
  693. 1> cc +L hello
  694. Aztec C68K 3.6a 12-18-87 (C) 1982-1987 by Manx software systems. Inc.
  695. Aztec 68000 Assembler 3.6a 12-18-87
  696. 1>
  697.  
  698. ......................................................................
  699.  
  700. Now Enter :
  701.  
  702. 1> ln hello.o -lm -lc
  703.  
  704.                                 PAGE 19
  705.  
  706. ----------------------------------------------------------------------
  707.  
  708. Aztec C should display the following on the screen. You're screen may
  709. differ slightly.
  710.  
  711. ......................................................................
  712.  
  713. 1> ln hello.o -lm -lc
  714. Aztec C68K linker 3.6a 12-18-87
  715. Base: 000000 Code: 001444 Data: 0002a0 Udata: 000050 Total: 001734
  716. 1>
  717.  
  718. ......................................................................
  719.  
  720. Did everything work as expected? If you didn't get an error, type the
  721. following DIR command in the CLI to see the current disk's directory. The
  722. executable program is stored there under the name HELLO. Notice that this
  723. file has no extension. There may also be other files with extensions of
  724. .MAP, .O, .LNK and of course .C. This shows that the extension helps
  725. identify the file. Call the executable program by entering the following
  726. line :
  727.  
  728.         hello
  729.  
  730. One the screen appears the text:
  731.  
  732. Hello, I am here!
  733.  
  734. The program isn't earth-shattering but this is only the beginning.
  735.  
  736.                                 PAGE 20
  737.  
  738. --------------------------------------------------------------------------
  739.  
  740. 3.3 ERROR MESSAGES
  741.  
  742. The most common mistake a new C programmer makes is omitting the semicolon
  743. following the closing parenthesis of the PRINTF function. This semicolon is
  744. one of the most widely used characters in C programs since it indicates the
  745. end of a statement. For this reason almost every C statement or function
  746. ends with a semi-colon. If the user omits it, the compiler reports many
  747. error messages. You might like to edit the hello.c file again and remove
  748. the semicolon. Save the file and try compiling the file again.
  749.  
  750. LATTICE :- 
  751.  
  752. If you forgot to type in the semicolon following the PRINTF function, the
  753. Lattice C compiler displays the following message:
  754.  
  755.         hello.c 5 Error 57: semi-colon expected.
  756.         Compiler returncode 1
  757.  
  758. AZTEC :-
  759.  
  760. The Aztec C compiler displays the following message if the semicolon is
  761. missing:
  762.  
  763.         hello.c: 5 ERROR 69: missing semi-colon
  764.         1 errors
  765.  
  766. Let's try to determine from this compiler message what is wrong with the
  767. file. The first line states the filename in which the error appeared:
  768. HELLO.C. That filename specification is useful later on (more on this
  769. later). Then follows the line number (5), error number (57) and the error
  770. description in English. This indicates that a semi-colon was expected in
  771. line 5.
  772.  
  773. The user must now reload the editor to correct the error:
  774.  
  775.         ED HELLO.C
  776.  
  777. You must include the extension of .C to edit the C source code.
  778.  
  779. To reach line 5, you can count down the lines (the fastest method for a
  780. progam this short). You can also press <ESC><M><5><RETURN> to get to line
  781. 5. The editor then moves the cursor to the line indicated.
  782.  
  783. Line 5 consists only of the closing brace (}), but this is expected since
  784. the error actually occured in the previous line. The semicolon in the
  785. previous line is missing. The error messages of the C compiler should never
  786. be taken to literally, since the search for the error may have to take the
  787. surrounding code lines into consideration.
  788.  
  789.                                 PAGE 21
  790.  
  791. --------------------------------------------------------------------------
  792.  
  793. After placing the semicolon where it belongs (following the PRINTF
  794. function), save the file again and try to compile the source code again. It
  795. should work.
  796.  
  797.                                 PAGE 22
  798.  
  799. ==========================================================================
  800.  
  801.                      CHAPTER 4 - THEORY AND PRACTISE.
  802.  
  803. Now you've had some practical experience entering and compiling a program,
  804. let's look at the theory of how the program in chapter 3 works.
  805.  
  806. You have two different types of keywords involved in C programming:
  807. functions and statements. The first line contains the function name VOID
  808. MAIN. The MAIN function is the most important element of a C program. The
  809. VOID means this program will not return a value and is inserted so that the
  810. compiler does not display a warning message. Without this function
  811. literally NOTHING runs.
  812.  
  813. A C program usually consists of up to a hundred functions. A function
  814. handles a part of the complete program, and is marked by parenthesis ().
  815. Braces ({}) mark the beginning and end of the function. These braces
  816. surround the statements and functions which the computer should execute.
  817. The following lines call functions;
  818.  
  819.         printf("hello");
  820.         Value(10);
  821.         music();
  822.         end();
  823.  
  824. and the following lines don't:
  825.  
  826.         value = old;
  827.         music;
  828.         end;
  829.  
  830. If you haven't compiled and linked the program in chapter 3, do so now.
  831. When you execute the program from CLI, a jump occurs first to the MAIN()
  832. function. This always happens, regardless of where the function appears in
  833. the listing. It can be at the beginning, end or middle of the program, but
  834. the main() function always executes first. The MAIN function calls the
  835. PRINTF function. The PRINTF function is stored in a library. All the user
  836. needs to know is the function name (printf), what it does (displays text on
  837. the screen) and what information it requires (text).
  838.  
  839. ARGUMENTS:
  840.  
  841. The information passed to a function during the call are arguments. The
  842. arguments to be passed are placed within the calling function's parenthesis
  843. to ensure proper delivery. It is important to enclose any character strings
  844. within quotation marks (e.g printf("Here I am!");).
  845.  
  846. After calling the PRINTF function the text appears on the screen. The
  847. PRINTF function ends and the program continues at the point where it was
  848. interrupted by the function call.
  849.  
  850.                                 PAGE 25
  851.  
  852. --------------------------------------------------------------------------
  853.  
  854. No other statements follow the line after PRINTF. This means that the main
  855. function has also reached it's end, and the program ends. The computer
  856. returns to the CLI, and additional commands can be entered.
  857.  
  858. The end of the main program and the return to CLI represent the termination
  859. of the MAIN function. The user should note how important this function is.
  860. It represents the C program itself; program execution starts and ends with
  861. the main function.
  862.  
  863.                                 PAGE 26
  864.  
  865. --------------------------------------------------------------------------
  866.  
  867. 4.1 PROGRAM FORMAT
  868.  
  869. Let's discuss the format of the program. The C compiler ignores any spaces,
  870. linefeeds and paragraph marks added to the listing by the user. Indenting
  871. lines or adding blank lines helps make source codes more readable to the
  872. user. Formatting has no effect on the execution speed or length of the
  873. final program. The program you entered in chapter 3 could have been in one
  874. of the following formats:
  875.  
  876.         void main () {
  877.              printf("Hello, Here I am!");
  878.              }
  879.  
  880.         void main ()
  881.         {
  882.              printf("Hello, Here I am!");
  883.              }
  884.  
  885.         void main() {printf("Hello, I am Here!");}
  886.  
  887. It's up to the user to select the version which appears to be most
  888. readable. Once you've selected a style stick with it. However, the last
  889. version above illustrates how even a small program can be made unreadable
  890. by 'formatting' it.
  891.  
  892. NOTE: 
  893.  
  894. All statements and functions must be entered in lowercase since C is case
  895. sensitive (it differentiates between upper and lower case letters). If you
  896. entered Printf or PRINTF instead of printf the linker reports an error
  897. since it can't find this function anywhere.
  898.  
  899.                                 PAGE 27
  900.  
  901. --------------------------------------------------------------------------
  902.  
  903. 4.2 DEFINING A FUNCTION
  904.  
  905. A function only executes the statements contained within the braces. If
  906. nothing is written there the computer does nothing. A program that does
  907. nothing is not very exiciting, but it's a good example. The floowing C
  908. source code compiles without problems (and does nothing).:
  909.  
  910.         void main()
  911.         {}
  912.  
  913. Don't expect miracles from the above program. When you compile, links and
  914. start it, it loads, runs and does nothing. The computer returns to the CLI.
  915.  
  916. DEFINITION:
  917.  
  918. The function arguments enclosed in the braces are it's definition. It
  919. defines what the computer should do when it executes a certain function.
  920.  
  921. A function can contain several statements or other function calls. Longer
  922. lines of text can be displayed on the screen with this program:
  923.  
  924.         void main()
  925.         {
  926.           printf("Hello, I have a question!\n");
  927.           printf("Do you believe in life without electricity?\n");
  928.           printf("Not me!\n");
  929.         }
  930.  
  931. The screen output will appear as follows:
  932.  
  933.         Hello, I have a question!
  934.         Do you believe in life without electricity?
  935.         Not me!
  936.  
  937. This program has two differences from the program in chapter 3. First,
  938. there are 3 printf instructions instead of one; second the \n character
  939. appears at the end of each string within quotation marks. See the next
  940. chapter for details on \n and other escape sequences.
  941.  
  942.                                 PAGE 28
  943.  
  944. --------------------------------------------------------------------------
  945.  
  946. 4.3 PRINTF AND ESCAPE SEQUENCES
  947.  
  948. The text as the end of section 4.2 appears on the screen as it appeared in
  949. the source code, with 3 exceptions. The three \n characters do not appear.
  950. The \n character is called the newline character, one of the many escape
  951. sequences used to control the formatting of text.  The \n character tells
  952. the compiler to insert a linefeed at that place in the text, just ass if
  953. you pressed the <return> key.
  954.  
  955. Any escapre sequences can be recognised by the backslash (\) preceding it.
  956. The character following indicates which escapte sequence should be
  957. executed. For example, the N signifies a linefeed: The computer starts the
  958. text after the \n at the beginning of the next line.
  959.  
  960. This newline (\n) escape sequence is important, since the printf function
  961. doesn't automatically add linefeeds after it displays text. You'll remember
  962. that when you ran the program in chapter 3, the prompt appeared right after
  963. the text. Basically C writes all characters sequentially on the screen,
  964. even if they are written with different function calls. The user must
  965. program the function to advance the line.
  966.  
  967. The user is not obligated place the escape sequences at the end of the
  968. character string. They can be placed between other "normal" characters or
  969. even at the beginning of the text. If desired, all three line can be
  970. writtein within one printf function:
  971.  
  972.         printf("Hello, I have a Question!\nDo you believe in life 
  973.         without electricity?\nNot me!\n");
  974.  
  975. This line is rather difficult to read. If you consistently place a newline
  976. (\n) character at the end of strings, programs will be much easier to read.
  977.  
  978. The newline character is not the only method of formatting text. The printf
  979. is comparable to the PRINT statment in BASIC or the WRITE statement in
  980. Pascal. The f in printf indicates that the text can be output in a
  981. specified format. This function can process and display character strings
  982. and other values as specified by the programmer. Since these capabilities
  983. are quite extensive, we'll introduce them to the reader as needed.
  984.  
  985.                              PAGE 29
  986.  
  987. --------------------------------------------------------------------------
  988.  
  989. 4.4 COMMENTS
  990.  
  991. The C language lets the programmer insert comments in the source code. This
  992. can be used to tell the reader what the source code is supposed to do.
  993. Comments have no effect on the speed or size of the compiled program.
  994. Comments start with the /* characters and end with the */ characters. The
  995. compiler skips over everything between the comment delimeters. Use comments
  996. liberally, since they never affect the final program and add to the
  997. readability of the source code.
  998.  
  999.         void main()
  1000.         {
  1001.         /* This program outputs a text which starts */
  1002.  
  1003.         printf("---Comments -- desired -- stop --\n");
  1004.         /* here ^ and ends over at the opposite end^ */
  1005.         }
  1006.  
  1007. Now think of your first program from chapter 3. If you added comments to
  1008. tell a future reader exactly what this program did and when, the end result
  1009. could look something like this:
  1010.  
  1011.         /* Program from chapter 3 of Schaun's book    */
  1012.         /* Amiga C for beginners from Abacus (C) 1988 */ 
  1013.         /* This program prints the words "hello, Here */
  1014.         /* I am " to the screen. Nothin else.         */
  1015.  
  1016.         #include <stdio.h>   /* Call standard i/o header file */
  1017.         void main()          /* main function */
  1018.         {                    /* start of function */
  1019.           printf("Hello, Here I am!"); /* show text on screen */
  1020.         }                    /* end of function */
  1021.  
  1022. This is a very exaggerated example. It doesn't matter if you comment a
  1023. program this clearly though, the comments are ignored by the compiler.
  1024.  
  1025.                                 PAGE 30
  1026.  
  1027. --------------------------------------------------------------------------
  1028.  
  1029. 4.5 VARAIBLES AND ARITHMETIC
  1030.  
  1031. Our knowledge of the C language is still rather small. Right now you can
  1032. display text on the screen and insert comments into source code.
  1033.  
  1034. It would be nice to be able to have a program accept input from the
  1035. keyboard. The SCANF function is the opposite of the PRINTF function - it
  1036. reads input instead of displaying output (more about scanf later).
  1037.  
  1038. Consider how a program would execute for questions and answers. First the
  1039. printf function would display the question on the screen. Next the SCANF
  1040. function reads the user's input.
  1041.  
  1042. For example, pretend that a number will be input as a response. The
  1043. following question asks for a number 1 to 2;
  1044.  
  1045.         Are you well?
  1046.         (1) = Yes, (2) = No
  1047.         Number:
  1048.  
  1049. The number must be stored somewhere. C provided a series of variable types
  1050. which can be used.
  1051.  
  1052. Variables allow certain types of information to be stored in a computer.
  1053. The variable type depends on the type of variable you want stored. There
  1054. are variables for characters, variables for strings , variables for
  1055. different kinds and sizes of numbers; and variables for combinations of
  1056. numbers.
  1057.  
  1058.  
  1059. 4.5.1 INTEGERS
  1060.  
  1061. The INT variable type represents integers (whole numbers). Variables of
  1062. type INT can accept whole numbers from approximately -32,768 to +32,767.
  1063. The following program uses integer variables, and introduces a practical
  1064. application of the SCANF function:
  1065.  
  1066.         /* scan1.c section 4.5 */
  1067.         void main()
  1068.         {
  1069.             int input;
  1070.  
  1071.             printf("Are you Well?\n");
  1072.             printf("(1) = Yes, (2) = No\n\n");
  1073.             printf("Number: ");
  1074.             scanf("%d",&input);
  1075.             printf("\n\nYour input was: %d\n",input);
  1076.         }
  1077.  
  1078.                                 PAGE 31
  1079.  
  1080.  
  1081.  
  1082. The first line of the maint function INT input;, tells the compiler what to
  1083. do with the variables. This line assigns a name to the variable. The
  1084. program uses this variable name for access to the  variable's contents. The
  1085. variable name (input) indicates it's purpose. Variable definition ends with
  1086. a semicolon.
  1087.  
  1088. The following lines are printf functions. Next, the SCANF function asks for
  1089. the user's input in response to the text "number : ". Since a large number
  1090. of data types exist, the input routine must be told what data can be
  1091. expected. The format specification %d specifies the data type. Format
  1092. specifications are similar to escape sequences (the characters preceeded by
  1093. a backslash). The percent sign indicates a format specification; the d
  1094. tells the SCANF that the value to be read in must be of type int. The name
  1095. of the desired variable follows the string in quotes, separated from the
  1096. string by a comma. An ampersand (&) preceeds the variable name. This is
  1097. important, if the system crashes the user should first examine the SCANF
  1098. function parameters to make sure they are correct.
  1099.  
  1100. If SCANF contains the correct information, the user can enter the input in
  1101. the running program. Enter a number and press the <return> key. This value
  1102. can be found in the variable 'input'. The program can now use this number.
  1103.  
  1104. This program accepts the input and then displays the variable using the
  1105. PRINTF function. The PRINTF function must also be told what kind of data it
  1106. must process. A format specification identical to the once which appears in
  1107. SCANF serves this purpose. Because of this, PRINTF knows that an integer
  1108. number will be passed, which must be placed at the location occupied by the
  1109. format specification in the text. The variable name INPUT follows the
  1110. string in quotes, separated from the string by a comma. The input appears
  1111. on the screen if the input was a 1 or 2 and not text (text is not allowed
  1112. here). If you enter text the input becomes a large random number (in
  1113. Lattice C) even though this number never appeared in the input line. If you
  1114. enter no input SCANF scrolls the screen one line upward and waits for a new
  1115. (more useful) input.
  1116.  
  1117.  
  1118.  
  1119. 4.5.2  THE IF STATEMENT.
  1120.  
  1121.  
  1122. It is rather boring just to let the computer repeat the input. It would be
  1123. better to respond to the input. For example, have the computer respond to
  1124. an entry of "1" with the message, "Thats very good", or an entry of "2"
  1125. where the message could be "I am sorry to hear that!".
  1126.  
  1127.                                 PAGE 32
  1128.  
  1129. --------------------------------------------------------------------------
  1130.  
  1131.  
  1132. The computer must be capable of comparing the value stored in input with
  1133. other numbers. depending on the results of this test, it must select one
  1134. text or the other text. In programming this is known as an If..THEN
  1135. construct. As in many other languages C also has this capability (C doesn't
  1136. require the THEN).
  1137.  
  1138. The variable is compared with 1. If the condition is found to be true, the
  1139. statement following the IF command executes. Here is an example:
  1140.  
  1141.         if(input==1)
  1142.           printf("That is very good!\n");
  1143.         if(input==2)
  1144.           printf("I am sorry to hear that!\n");
  1145.  
  1146. The conditions appear inside the parenthesis so that the first printf
  1147. statement only occurs when input equals 1. The same is true of the
  1148. following if statement, with the difference that the text executes if input
  1149. equals 2. Semicolons never follow the IF.
  1150.  
  1151. The user who wants to experiment can try a semicolon after the second if.
  1152. If you do so, the program acts as if line if(input==2); doesn't exist.
  1153. After each input "I am sorry to hear that!" appears.
  1154.  
  1155. Adding the four lines above makes the program run properly, but it could be
  1156. improved. Some users may be familiar with the BASIC statement:
  1157.  
  1158.         IF A = 1 THEN PRINT "THAT IS VERY GOOD!":
  1159.             ELSE PRINT "I AM SORRY TO HEAR THAT"
  1160.  
  1161.  
  1162. ELSE :-
  1163.  
  1164. The C language also has an ELSE statment which can only be used together
  1165. with the IF statement. The ELSE statement executes only when the condition
  1166. has not been met. This eliminates the second test:
  1167.  
  1168.         if(input==1)
  1169.            printf("That is very good!\n");
  1170.         else
  1171.            printf("I am sorry to hear that!\n);
  1172.  
  1173. The second test is now improved. A modified version of the C program now
  1174. appears as follows;
  1175.  
  1176.         /* scan2.c 4.5.2 */
  1177.  
  1178.         void main()
  1179.         {
  1180.            int input;
  1181.  
  1182.                 printf("Are you Well?\n");
  1183.                 printf("(1) = Yes, (2) = No\n\n");
  1184.                 printf("Input Number: ");
  1185.                 scanf("%d",&input);
  1186.                 if(input == 1 )
  1187.                    printf("That is very good!\n");
  1188.                 elese
  1189.                    printf("I am sorry to hear that!\n");
  1190.         }
  1191.  
  1192.                                 PAGE 33
  1193.  
  1194.  
  1195. If several commands should be executed after the If (e.g. two printf
  1196. functions), the second line cannot be written immediately after it. The
  1197. following example wouldn't work:
  1198.  
  1199.         if(input==1)
  1200.           printf("That is very good!\n");
  1201.           printf("Hope you stay healthy!\n); /* not like this */
  1202.         else
  1203.           printf("I am sorry to hear that!\n");
  1204.  
  1205. STATEMENT BLOCK
  1206.  
  1207. Since only one line is executed after the IF, something else must be done.
  1208. Up to now only one statement has been described. It is time to describe a
  1209. statement block. Placing several statements inside braces creates a
  1210. statement block which is valid as a unit. This block can be placed
  1211. following the If statement without problems;
  1212.  
  1213.         if(input==1)
  1214.           {
  1215.             printf("That is very good!\n");
  1216.             printf("Hope you stay healthy!\n");
  1217.           }
  1218.         else
  1219.           printf("I am sorry to hear that!\n");
  1220.  
  1221. The Amiga can do a lot of things, but what it does best is calculate (and
  1222. fast). Let's start with addition. To add two values together use the plus
  1223. sign (+):
  1224.  
  1225.         sum = number1 + number2
  1226.  
  1227. The result for this example is stored in the variable sum. This variable
  1228. must be defined at the beginning of the function, just like all variables.
  1229. Using type INT, the following definition results;
  1230.  
  1231.         int sum
  1232.         int number1
  1233.         int number2
  1234.  
  1235. C is a language for lazy people. Most everything can be changed to
  1236. abbreviations to cut down on keyboard use. Those who wnat to become good C
  1237. programmers should use this capability. These three data values are defined
  1238. as the same variable type. You only need to enter INT once, all integer
  1239. variables can be listed following the single INT:
  1240.  
  1241.         int sum, number1, number2;
  1242.  
  1243. All variables are separated by commas and the list is terminated with the
  1244. semicolon.
  1245.  
  1246.                                 PAGE 34
  1247.  
  1248.  
  1249.  
  1250. With this information it is possible to write a program that adds two
  1251. numbers. The SCANF function permits data input, but this time two numbers
  1252. will be read in. This will not be done with two separate function calls
  1253. (this would also be possible), but a second format specification is written
  1254. into the string of the SCANF call. If contains %d%d (notice no spaces)
  1255. which reads the second parameter. And now the listing:
  1256.  
  1257.         /* scan3.c .4.5.2 */
  1258.         void main()
  1259.         {
  1260.           int sum, number1, number2;
  1261.  
  1262.           printf("Please input two numbers!\n");
  1263.           scanf("d%d",&number1,&number2);
  1264.           sum = number1 + number2;
  1265.           printf("%d + %d = %d\n", number1, number2, sum);
  1266.         }
  1267.  
  1268. The user familiar with other langauges such as BASIC can compare the
  1269. listings to other language implementations of the same program. The last
  1270. PRINTF function with the three format specifications can appear confusing.
  1271. The following is a BASIC equivalent:
  1272.  
  1273.         PRINT "please input two numbers!"
  1274.           INPUT N1,N2
  1275.           SUM = N1 + N2
  1276.         PRINT N1;" + ";N2;" = ";SUM
  1277.  
  1278.  
  1279.  
  1280.  
  1281. 4.5.3 CALCULATING WITH C
  1282.  
  1283.  
  1284. The reader can guess what would have to be changed to perform
  1285. multiplication instead of addition. The plus sign is replaced by an
  1286. asterisk (*). A hyphen (-) is used for subtraction and a slash (/) performs
  1287. division.
  1288.  
  1289. Calculations may be performed with constant values as well as variables.
  1290. Both constants and variables can be mixed. Some examples follow to
  1291. illustrate. It is assumed that all variables are defined and contain
  1292. meaningful values:
  1293.  
  1294.         result = number * 4;
  1295.         sum = var + 2 + var2 + 3 + var4;
  1296.         result = 4 * 5 - 7 / var;
  1297.         value = 2 * (number - 7);
  1298.         result = 4 + 5 * 3 - 2;
  1299.         counter = counter + 1;
  1300.  
  1301. Evaluating a formula is as simple as entering it into a pocket calculator.
  1302. C recognises the laws of mathematical precedence:
  1303.  
  1304.                                 PAGE 35
  1305.  
  1306.  
  1307.  
  1308.         result = 4 + 5 * 3 - 2;
  1309.  
  1310. The result is 17, not 25. The product of 5 * 3 is calculated first, after
  1311. which 4 is added and two subtracted.  
  1312.  
  1313. The counter = counter + 1; example above deserves special attention. This
  1314. equation is unsolvable for the normal person but no problem for the
  1315. computer. It takes the content of the variable COUNTER, adds one to it and
  1316. stored the result in counter. This operation increments the content of the
  1317. variable by one for every call.  
  1318.  
  1319. Let's write a comprehensive program for performing math equations. The
  1320. assumptions are that all basic four mathematical functions are performed
  1321. with two variables. A SCANF function reads the numbers. Then the numbers
  1322. are tested with several IF statements to determine which mathematical
  1323. function should be performed. The result is calculated accordingly. If an
  1324. invalid code is input, a message appears;
  1325.  
  1326.         /* math1.c 4.5.3 */
  1327.         void main()
  1328.         {
  1329.            int number1, number2, result, operator, error;
  1330.  
  1331.            printf("Please input Two Numbers! \n");
  1332.            scanf("%d%d",&number1,&number2);
  1333.            printf("And now the code for the Operation!\n");
  1334.            printf("1=Add, 2=Subtract, 3=Multiply, 4=Divide\n");
  1335.            scanf("%d", &operator);
  1336.            error = 1;
  1337.            if(operator==1) /* add */
  1338.               {
  1339.                 result = number1 + number2;
  1340.                 error = 0;
  1341.               }
  1342.            if(operator==2) /* subtract */
  1343.               {
  1344.                 result = number1 - number2;
  1345.                 error = 0;
  1346.               }
  1347.            if(operator==3) /* multiply */
  1348.               {
  1349.                 result = number1 * number2;
  1350.                 error = 0;
  1351.               }
  1352.            if(operator==4) /* divide */
  1353.               {
  1354.                 result = number1 / number2;
  1355.                 error = 0;
  1356.               }
  1357.            if(error==1) /* none of the above */
  1358.               printf("Wrong Code! Input only numbers 1-4!\n");
  1359.            else
  1360.               printf("The result is %d\n",result);
  1361.         }
  1362.  
  1363.                                 PAGE 36
  1364.  
  1365.  
  1366. The above program is very easy to read. After all the values have been read
  1367. the variable ERROR is assigned the value of 1. During every operation that
  1368. follows, be it addition, subtraction etc.. the ERROR value is set to zero.
  1369. This makes it possible to determine whether one of the four operations was
  1370. performed. If this was not true the value in OPERATOR is illegal.
  1371.  
  1372. Before the output, the result it tested to determine if it was calculated.
  1373. This can only be seen in the variable ERROR.
  1374.  
  1375. Test this program thoroughly with various values. Please note that the
  1376. integer variables are only permitted to store values between +32767 and
  1377. -32768. Furthermore, division by zero should be avoided. This would cause a
  1378. system crash and a Guru Meditation.
  1379.  
  1380.  
  1381. 4.5.4 FLOATING POINT NUMBERS
  1382.  
  1383. Perhaps you have noticed something else. Try dividing 9 by 2. The result
  1384. displayed by the computer is 4, which is incorrect (4.5 would be right).
  1385. Isn't this expensive computer capable of performing correct division?.
  1386.  
  1387. The error can be traced from the variable type. The INT variable type is
  1388. only capable of processing whole numbers between +- 32000. The value 4.5 is
  1389. a floating point number not a whole number. If during a division sa
  1390. remainder (the fraction after the decimal point) occurs, it is ignored.
  1391. This does not mean that the division 9/2 cannot be performed on the Amiga
  1392. computer. The only thing required is that the variable type can be capable
  1393. of storing floating point numbers. No problem since C is equipped for this.
  1394.  
  1395. To convert the current program for this new data type, the variables
  1396. number1, number2 and result must be changed. This process consists only of
  1397. replacing INT with FLOAT. The first lines appear as follows;
  1398.  
  1399.         main()
  1400.         {
  1401.           float number1, number2, result;
  1402.           int operator, error;
  1403.         }
  1404.  
  1405. This alone is not sufficient since SCANF and PRINTF use the format
  1406. specification %d which expects an integer value. This is no longer the
  1407. case. The %d must be replaced with %f. The F means a floating point value
  1408. is passed just like the d used for integer values. 
  1409.  
  1410.                                 PAGE 37
  1411.  
  1412.  
  1413.  
  1414. The first SCANF function now appears as follows:
  1415.  
  1416.         scanf("%f%f",&number1,&number2);
  1417.  
  1418. The last PRINTF function must also be changed. The variable RESULT is now a
  1419. floating point value. The d is replaced with f. Newly compiled and linked,
  1420. this version makes error free computations of floating point numbers
  1421. possible. Numbers stored as type float are practically unlimited in size.
  1422. Millions, and even billions and billions, can be calculated. Here is the
  1423. complete program: 
  1424.  
  1425.  
  1426.         /* math1.c 4.5.4 */
  1427.         void main()
  1428.         {
  1429.            float number1, number2, result;
  1430.            int operator, error;
  1431.  
  1432.            printf("Please input Two Numbers! \n");
  1433.            scanf("%f%f",&number1,&number2);
  1434.            printf("And now the code for the Operation!\n");
  1435.            printf("1=Add, 2=Subtract, 3=Multiply, 4=Divide\n");
  1436.            scanf("%d", &operator);
  1437.            error = 1;
  1438.            if(operator==1) /* add */
  1439.               {
  1440.                 result = number1 + number2;
  1441.                 error = 0;
  1442.               }
  1443.            if(operator==2) /* subtract */
  1444.               {
  1445.                 result = number1 - number2;
  1446.                 error = 0;
  1447.               }
  1448.            if(operator==3) /* multiply */
  1449.               {
  1450.                 result = number1 * number2;
  1451.                 error = 0;
  1452.               }
  1453.            if(operator==4) /* divide */
  1454.               {
  1455.                 result = number1 / number2;
  1456.                 error = 0;
  1457.               }
  1458.            if(error==1) /* none of the above */
  1459.               printf("Wrong Code! Input only numbers 1-4!\n");
  1460.            else
  1461.               printf("The result is %f\n",result);
  1462.         }
  1463.  
  1464. LATTICE:
  1465.  
  1466. The library for mathematical and floating point numbers must be linked with
  1467. the standard library. Example :
  1468.  
  1469.         lc -Lm math2
  1470.  
  1471.  
  1472.                                 PAGE 38
  1473.  
  1474. AZTEC:
  1475.  
  1476. If you work with the Aztec C compiler, the library for mathematical
  1477. functions and floating point numbers must be linked with the standard
  1478. library c.lib.
  1479.  
  1480. Example :  cc +L math2.c
  1481.            ln math2.o -lm -lc
  1482.  
  1483.  
  1484. 4.5 CHARACTERS AND CHARACTER STRINGS.
  1485.  
  1486. Besides the INT and FLOAT variable types which accept numbers, you need
  1487. another category of variable to store characters. It would be better if the
  1488. program above could accept a plus sign instead of the number 1 to indicate
  1489. addition. The data type CHAR allows variables to be defined which can
  1490. accept characters.
  1491.  
  1492. The syntax for definition of a CHAR variable is exactly as described in the
  1493. FLOAT and INT variables;
  1494.  
  1495.         char character;
  1496.  
  1497. This type of variable has it's own format specification for the PRINTF and
  1498. SCANF functions. A c is used for type CHAR. To give the calculation program
  1499. a few extras, the operator is entered as a character. This means that
  1500. instead of entering a number as you had to before, you can enter a math
  1501. operator instead.
  1502.  
  1503. Another improvement can be made at this point. The format for entering
  1504. equations should be similar to that of a pocket calculator (i.e first
  1505. number, operator, second number). You should be able to press the <return>
  1506. or <enter> key instead of the <=> key. Since the SCANF function is
  1507. flexible, the following change is sufficient to make this possible;
  1508.  
  1509.         scanf("%f%c%f", &number1, &operator, &number2);
  1510.  
  1511. The %c between the two format specifications indicates character input.
  1512.  
  1513. The tests which formerly checked the code now have to test the characters
  1514. for the operators. Nothing easier than that! Only characters must be
  1515. placed in apostrophes (single quotes):
  1516.  
  1517.         if(operator=='+')
  1518.             .......
  1519.  
  1520.                                 PAGE 39
  1521.  
  1522.  
  1523. After all the small changes, compare this version to the final program
  1524. below in which some other cosmetic changes were made. The reader should now
  1525. be able to understand the additions made.
  1526.  
  1527. During the inpput a small item has changed. Until now the <return> key had
  1528. to be pressed (but not required) after inputting each number. Now the
  1529. entire input must be in one line. The reason for this is the fact that a
  1530. single character is read in with %c. This could be a return or a space. For
  1531. this reason the first number is followed immediately by the operator after
  1532. which the <return> key may be pressed, if desired. Finally the second
  1533. numberr appears as in this line:
  1534.  
  1535.         15.50000* 12.50000 = 193.750000
  1536.  
  1537. Here is the final version of the program :
  1538.  
  1539.         /* math3.c 4.5.5 */
  1540.         void main()
  1541.         {
  1542.            float number1, number2, result;
  1543.            char operator;
  1544.            int error;
  1545.  
  1546.            printf("Input format : Number1, Operator, Number2 (No
  1547.                    spaces)!\n");
  1548.            scanf("%f%c%f",&number1,&operator,&number2);
  1549.            error = 1;
  1550.            if(operator=='+') /* addition */
  1551.                 {
  1552.                 result = number1 + number2;
  1553.                 error = 0;
  1554.                 }
  1555.            if(operator=='-') /* subtraction */
  1556.                 {
  1557.                 result = number1 - number2;
  1558.                 error = 0;
  1559.                 }
  1560.            if(operator=='*') /* Multiplication */
  1561.                 {
  1562.                 result = number1 * number2;
  1563.                 error = 0;
  1564.                 }
  1565.            if(operator=='/') /* division */
  1566.                 {
  1567.                 result = number1 / number2;
  1568.                 error = 0;
  1569.                 }
  1570.            if(error==1) /* none of the above */
  1571.                 printf("Wrong Operator %c !\n",operator);
  1572.            else
  1573.                 printf("%f %c %f = %f\n",number1, operator, number2,
  1574.                         result);
  1575.         }
  1576.  
  1577.                                 PAGE 40
  1578.  
  1579.  
  1580. LATTICE :
  1581.         
  1582. The library for mathematical functions and floating point numbers must be
  1583. linked to the standard library. Example :
  1584.  
  1585.         lc -Lm math3
  1586.  
  1587.  
  1588.  
  1589. AZTEC  :
  1590.         
  1591. If you work with the Aztec C compiler, the library for mathematical
  1592. functions and floating point numbers must be linked with the standard
  1593. library c.lib. For example :
  1594.  
  1595.         cc +L math3.c
  1596.         ln math3.o -lm -lc
  1597.  
  1598.  
  1599.  
  1600.  
  1601.                                 PAGE 41
  1602.  
  1603. ==========================================================================
  1604.  
  1605.                         CHAPTER 5 - LOOPS.
  1606.  
  1607.  
  1608. The programs presented up until now execute straight from beginning to end.
  1609. An if statment may skip over some spots but we havn't jumped to earlier
  1610. statements. Loops branch to earlier sections of the program.
  1611.  
  1612. 5.1 WHILE LOOPS
  1613.  
  1614. The while statement is followed by two parenthesis which surround the
  1615. desired arguments. An example makes this clear;
  1616.  
  1617.         void main()
  1618.         {
  1619.           int counter;
  1620.  
  1621.           counter = 15;
  1622.           while(counter>0)
  1623.            {
  1624.               printf("counter is %d\n",counter);
  1625.               counter = counter - 1;
  1626.             }
  1627.         }
  1628.  
  1629. The block which appears after the WHILE statement executes until the
  1630. conditions inside the parenthesis are true. In the beginning, the variable
  1631. COUNTER is set to 15. While the Condition COUNTER>0 has been met, the
  1632. following block is executed which outputs the current value of COUNTER and
  1633. then decrements it by one. In this case the PRINTF function is called 15
  1634. times until COUNTER has been reduced to zero. The conditional statements
  1635. can be formed by using tests for equality (==), greater than (>), less than
  1636. (<), greater than or equal to (>=), or less than or equal to (<=). The
  1637. comparison here is for COUNTER to be greater than zero.
  1638.  
  1639. The comparison operators for C are similar to those found in most
  1640. programming languages.
  1641.  
  1642.                                 PAGE 45
  1643.  
  1644.  
  1645.         <    less than
  1646.         <=   less than or equal to
  1647.         >    greater than
  1648.         >=   greater than or equal to
  1649.         ==   equal to
  1650.         !=   unequal to
  1651.  
  1652. Instead of 
  1653.         
  1654.         while(counter>0)
  1655.  
  1656. the following could be written:
  1657.  
  1658.         while(counter>=1)
  1659.  
  1660. The latter is preferred since the limit is explicitly provided. To
  1661. construct a loop which counts up to to value 100 it is recommended to use
  1662. this value in the test:
  1663.  
  1664.         while(counter<=100)
  1665.  
  1666. In the comparison operators <= and >=, the equal sign (=) always appears at
  1667. the end.
  1668.  
  1669. FACTORIALS.
  1670.  
  1671. A practical example is the calculation of a factorial number through
  1672. constant multiplication. A factorial in mathematics is the multiplication
  1673. of all whole numbers up to a set value. The factorial of 4 therefore is:
  1674.  
  1675.         4! = 1 * 2 * 3 * 4 = 24
  1676.  
  1677. Here is our example program:
  1678.  
  1679.         /* factorial.c 5.1 */
  1680.         void main()
  1681.         {
  1682.         
  1683.           int num, i;
  1684.           float factorial;
  1685.  
  1686.           printf("Please input a number : ");
  1687.           scanf("%d",&num);
  1688.           i = num;
  1689.           factorial = 1; /* initialise */
  1690.           while(i>= 1)
  1691.              {
  1692.                 factorial = factorial * i;
  1693.                 i = i - 1;
  1694.              }
  1695.           prinf("%d! = %f\n",num,factorial);
  1696.         }
  1697.  
  1698.                                 PAGE 46
  1699.  
  1700.  
  1701.  
  1702. Now for a few hints in helping you compile this program with your compiler.
  1703.  
  1704. LATTICE :
  1705.  
  1706. The library for mathematical functions and floating point numbers must be
  1707. linked with the standard library. Example:
  1708.  
  1709.         lc -Lm factorial
  1710.  
  1711.  
  1712. AZTEC:
  1713.  
  1714. If you work with the Aztec C compiler, the library for mathematical
  1715. functions and floating point numbers must be linked with the standard
  1716. library c.lib. Example:
  1717.  
  1718.         cc +L factorial.c
  1719.         ln factorial.o -lm -lc
  1720.  
  1721.  
  1722.  
  1723.  
  1724.  
  1725.                                 PAGE 47
  1726.  
  1727. --------------------------------------------------------------------------
  1728.  
  1729. 5.2 FOR LOOPS
  1730.  
  1731. Another loop can be constructed using the FOR statement. In BASIC the
  1732. command is used as follows;
  1733.  
  1734.  
  1735.         FOR I = 1 TO 100 STEP 2
  1736.            ........
  1737.         NEXT I
  1738.  
  1739. In C this appears as follows:
  1740.  
  1741.         for(i=0; i<=100; i=i+2)
  1742.             ......
  1743.  
  1744. C doesn't require a NEXT as in BASIC, since only the statement block
  1745. following the loop header is executed. Within the parenthesis are some
  1746. interesting items. There are three individual statements separated from
  1747. each other by semicolons. A semicolon does not follow the last entry. The
  1748. loop body ends here with the closing parenthesis. The first entry i=0
  1749. assigns a starting value to the variable which is modified within the loop.
  1750. The statement i<=100 represents the ending condition. Until it is satisfied
  1751. the loop executes. The last part of the loop body increments or decrements
  1752. the control variables which were previously initialised with a starting
  1753. value.
  1754.  
  1755.  
  1756.                                 PAGE 48
  1757.  
  1758. --------------------------------------------------------------------------
  1759.  
  1760. 5.3 DO WHILE LOOPS
  1761.  
  1762. The last type of loop is the DO..WHILE loop. The reader has already read
  1763. about the WHILE loopl this loop is quite similar. Please compare the two
  1764. program sections below:
  1765.  
  1766.         /* first program section */
  1767.         while(i > 0)
  1768.           {
  1769.             i = i - 1;
  1770.             printf("i is %d\n",i);
  1771.           {
  1772.  
  1773.         /* second program section */
  1774.         do
  1775.           {
  1776.             i = i - 1;
  1777.             printf("i is %d\n",i);
  1778.            } while(i>0);
  1779.  
  1780. The DO begins the DO..WHILE loop, and WHILE ends the loop. This leads to a
  1781. small but significant difference in program execution. In the first example
  1782. the program checks if variable i is greater than 0 and then executes the
  1783. loop only if the conditions are met. In the second example the test is
  1784. executed only after the loop has already been executed once. If i contains
  1785. the value zero, the WHILE loop is skipped, unlike the DO..WHILE loop which
  1786. executes at least once.
  1787.  
  1788. Please note the semicolon which must follow the WHILE. It is often
  1789. forgotten since normal WHILE loops don't use semicolons.
  1790.  
  1791. If this material is not clear without further example programs, the user is
  1792. encouraged to write some short programs (e.g. which output the values of
  1793. the variables used).
  1794.  
  1795.  
  1796. 5.3.1 MORE ERROR CHECKING.
  1797.  
  1798. The next section deals with error detection. Up to now it was difficult to
  1799. make mistakes, except for error in typing. When the program suddenly
  1800. reports errors, there's no need to panic. Study the message the C compiler
  1801. returns. You may have to do a little thinking to detect cleverly hidden
  1802. errors.
  1803.  
  1804.  
  1805.                                 PAGE 49
  1806.  
  1807.  
  1808. Below is a new program. Based on what you know so far you should be able to
  1809. determine where the errors are hidden, and which lines could cause
  1810. problems. The listing contains errors which result in a long series of
  1811. error messages. Try to find the hidden errors on your own first. Fix these
  1812. errors then try compiling the source code to see what you missed. We've
  1813. included the solution directly after the listing. The program should add
  1814. all numbers from 1 to 100 and display the sub-totals and final total on the
  1815. screen:
  1816.  
  1817.         main();
  1818.         {
  1819.           printf("I add all numbers from 1 to 100/n");
  1820.  
  1821.           i=1;
  1822.           do
  1823.  
  1824.              printf("Subtotal for %d. Value : %d/n",i,sum);
  1825.              sum = sum + 1;
  1826.              i = i + 1;
  1827.           while(i < 100)
  1828.           printf("Sum of all numbers to 100 is %d/n",sum);
  1829.         }
  1830.  
  1831. Did you find all the errors? You should have found most of them since the
  1832. program is almost completely wrong! Even if you found no errors you can
  1833. follow the remaining material without problems.
  1834.  
  1835. Let's start with the first line which contains an error (of course). The
  1836. semicolon following MAIN shouldn't be there. The missing VOID only results
  1837. in a warning not an error. The next line with the brace is correct (an
  1838. exception in this program). The compiler accepts the first printf function
  1839. without problems. It doesn't contain a syntax error. The line would even be
  1840. right if you wanted to display the slash (/) and an N. The slash (/) should
  1841. have been a backslash (\). To be consistent this error occured in all the
  1842. PRINTF functions in this program.  
  1843.  
  1844. THe assignment i=1; is correct. The DO..WHILE loop which should execute the
  1845. following three lines, has no braces (the braces make the three lines into
  1846. a statement block). The semicolon is also missing after the WHILE( i<100)
  1847. line.
  1848.  
  1849. Within the loop the values for i and SUM should be displayed. Except for
  1850. the error with the /n everything is correct here. Finally the program
  1851. increments the contents of sum and i are incremented (NOTE :- the bad
  1852. formation of this text is in the original  and I have just copied it
  1853. exactly as in the book - RAZOR BLADE.). Trouble is, the SUM variable was
  1854. never defined. The C  compiler doesn't know what is meant by i and sum. A
  1855. line must be added before the PRINTF function:
  1856.  
  1857.         int sum, i;
  1858.  
  1859. Before or after i=1; a sum=0; must be added. After these changes the C
  1860. compiler is happy but the program will not display the right output. There
  1861. are two logical errors in the program.
  1862.  
  1863.  
  1864.                                 PAGE 50
  1865.  
  1866. The first occurs as the sub-total is displayed. The value of SUM is
  1867. displayed before it has been calculated. The line sum = sum + 1 must be
  1868. placed before the line with :
  1869.  
  1870.         printf("sub-total for %d. Value : %d\n",i, sum);
  1871.  
  1872. The WHILE test remains which terminates the program after the number 99.
  1873. The change is simple:
  1874.  
  1875.         } while(i <= 100);
  1876.  
  1877. The error free version of the program appears below;
  1878.  
  1879.         /* errorfree.c 5.3.1 */
  1880.         void main()
  1881.         {
  1882.           int sum, i;
  1883.           printf("I add all numbers from 1 to 100\n");
  1884.  
  1885.           sum = 0;
  1886.           i = 1;
  1887.           do
  1888.            {
  1889.              sum = sum + i;
  1890.              printf("Subtotal for %d. Value : %d\n", i,sum);
  1891.              i = i +1;
  1892.            } while( i<=100 )
  1893.           printf("Sum of all numbers to 100 is %d\n", sum);
  1894.         }
  1895.  
  1896.  
  1897.                                 PAGE 51
  1898.  
  1899. --------------------------------------------------------------------------
  1900.  
  1901. 5.4 AND and OR
  1902.  
  1903. Up to this point only one condition can be check in your loop. This changes
  1904. with the introduction of the && and || operators. The <|> key can be found
  1905. on the right side of the keyboard above the <return> key. The && represents
  1906. the logical AND and the || the logical OR. Why these operators are called
  1907. logical will be revealed later since other logical operators also exist in
  1908. C. From BASIC the commands AND and OR are familiar and they are the same as
  1909. the operators in C.
  1910.  
  1911. AND:
  1912.  
  1913. Connecting two conditions with AND:
  1914.  
  1915.         while(i <= 10 && i >= 5)
  1916.                 .......
  1917.  
  1918. The loop is now executed when 
  1919.  
  1920.         . i is less than or equal to 10
  1921.         . i is greater than or equal to 5
  1922.  
  1923. If one of the two criteria is not met (e.g i=4 , the entire condition is
  1924. false and therefore not satisfied. Only if both tests are true can the loop
  1925. be executed.
  1926.  
  1927.  
  1928. OR:
  1929.  
  1930. Or is used as it is in daily conversation. If one of the two conditions is
  1931. true the entire expression is true. The next example assumes that a
  1932. character variable should be tested for a certain comment. Since the
  1933. logical connections can be used with other conditional tests, they can be
  1934. used together with IF:
  1935.  
  1936.         if(operator=='+' || operator=='-' || operator=='*' || operator 
  1937.            =='/')
  1938.         printf("The operator is valid!\n");
  1939.  
  1940. Four tests were made of which only one must be true. If several tests can
  1941. be positive then this is no problem since only one true condition is
  1942. sufficient. That the IF statement could be written in two lines should be
  1943. nothing new. Rememeber that the formatting of the C listing is of no
  1944. interest to the C compiler.
  1945.  
  1946. NEGATION:
  1947.  
  1948. There is another operator to be discussed. This is the negation operator !,
  1949. mentioned as part of the inequality operator !=. With this character all
  1950. tests and returns can be made into the opposite. If a test should be made
  1951. to determine if a character is not an arithmetic operator, the following
  1952. test can be devised:
  1953.  
  1954.  
  1955.                                 PAGE 52
  1956.  
  1957.  
  1958.         if !(operator=='+' || operator=='-' || operator=='*' || operator 
  1959.            =='/')
  1960.         printf("Not a valid operator!\n");
  1961.  
  1962. All tests are made within the parenthesis. If the expression inside the
  1963. parenthesis is true, a valid character is present, the negation operator
  1964. goes into action. It simply reverses the matter. From the true test it
  1965. makes a false one so that the PRINTF command is not executed. This is
  1966. similar to the false test result within the parenthesis, when none of the
  1967. signs +-*/ are stored in the variable. In this case the ! operator makes it
  1968. a true test. That is the same procedure as inserting a NOT into a sentence.
  1969. In everyday English double negatives can be used in one sentence, but not
  1970. many people will understand it.
  1971.  
  1972.                                 PAGE 53
  1973.  
  1974. ==========================================================================
  1975.  
  1976.                         CHAPTER 6 - STRINGS.
  1977.  
  1978. You've entered strings and displayed them on the screen in previous
  1979. chapters. What else can you do with them? The following code shows string
  1980. variable definition.
  1981.  
  1982.         char name[number_of_fields];
  1983.  
  1984. Strings consist of groups of individual characters of type CHAR. The above
  1985. variable definition tells the compiler the maximum number of characters the
  1986. string can have. If you want to process a single character belonging to the
  1987. string, you can't just call the variable - you'll get the entire string. In
  1988. addition, you must know the exact location in the string at which you can
  1989. find the specific character. You'd enter the number of the character in
  1990. brackets, just as you did in the definition. 
  1991.  
  1992. Let's take the first character in a string. This first character appears in
  1993. the first position of the string, and is assigned position 0 (computers
  1994. always start counting with zero). All locations then shift by one. The
  1995. second character can be reached using the value 2, due to the index, which
  1996. acts as a position indicator. Every position contains a character. All
  1997. characters are arranged sequentially in a large or small string.
  1998.  
  1999.  
  2000. 6.1 BACKTRACKING.
  2001.  
  2002. Let's write a program which displays the text backwards on the screen.
  2003. Before starting you must assume that a string can be any length. The string
  2004. will always end with the value 0 (null). The last character of the string
  2005. must be processed first if you want the text displayed backwards. The
  2006. program needs a small FOR loop to find the last character of the string (0)
  2007. :
  2008.  
  2009.         .....
  2010.         char input[80];
  2011.  
  2012.         for(index=0;input[index] !=0; index = index + 1)
  2013.             ;
  2014.         ......
  2015.  
  2016. The loop body (the statements executed during every passs through the loop)
  2017. is empty. A single semicolon follows the FOR loop. Since a block of
  2018. statements follow every loop, this semicolon ends a block that does
  2019. nothing.
  2020.  
  2021.                                 PAGE 57
  2022.  
  2023.  
  2024.  
  2025. This is the empty statement. The data in parenthesis perform all of the
  2026. required operations. First the index is set to 0. Then the test follows
  2027. which determines whether a character is not equal to 0. If the condition is
  2028. satisfied to index is increased by one. The last element of the string
  2029. contains a zero and the loop ends. The result in index is the length of the
  2030. string. The last character of the string is located one position before the
  2031. null value. Therefore the index variable must be reduced by one before
  2032. being used. The index counts down to zero one step at a time and the
  2033. program displays a character at every step.
  2034.  
  2035.         do
  2036.            {
  2037.               index = index - 1;
  2038.               printf("%c",input[index]);
  2039.  
  2040.            } while(index > 0);
  2041.  
  2042. You now have the information you need to write the entire program. One
  2043. other item before you enter and compile the program; If you have the Aztec
  2044. C  compiler, this program will not compile using the +L (longwords) option.
  2045. Omit this option when compiling the program with Aztec C. Here's the source
  2046. code :
  2047.  
  2048.         /* backwards 6.1 */
  2049.         void main()
  2050.         {
  2051.            char input[81];
  2052.            int index;
  2053.  
  2054.            printf("Please input some text!\n");
  2055.            scanf("%s",input); /* Strings do not require & */
  2056.  
  2057.            for(index = 0; input[index] !=0; index = index + 1)
  2058.                 ; /* search for end mark */
  2059.  
  2060.            printf("Your input >%s< has %d characters \n",input, index);
  2061.  
  2062.            do
  2063.              {
  2064.                index = index - 1;
  2065.                printf("%c",input[index]);
  2066.              }while(index > 0);
  2067.  
  2068.            printf("\n\n"); /* Blank lines before prompt */
  2069.  
  2070.                                 PAGE 58
  2071.  
  2072. ==========================================================================
  2073.  
  2074.                      CHAPTER 7 - CALCULATING IN C
  2075.  
  2076. You have already seen how fast the Amiga computes; addition(+),
  2077. subtraction(-), multiplication(*) and division(/) are familiar to you.
  2078.  
  2079. The modulo operator (%) performs another mathematical operation - modulo
  2080. division, which calculates the remainder of an integer division. THe result
  2081. is assigned to a variable using the equal sign, where the variable must be
  2082. to the left of the assignment operator. The general format is as follows:
  2083.  
  2084.         variable = operand1 <> operand2
  2085.         (<> represents the operator)
  2086.  
  2087. Frist the program calculates the expression to the right of the equal sign
  2088. and places the result in the variable to the left of the equal sign.
  2089. Because of this statements such as the following are possible:
  2090.  
  2091.         variable = variable + 1;
  2092.  
  2093. The expression is impossible in normal math, but poses no problem for the
  2094. computer. The computer reads the variable content, adds one and stores the
  2095. result in the same variable. Combinations of math operators are possible as
  2096. the following examples show:
  2097.  
  2098.         number = 3 * 32
  2099.         number = 2 + 6 * 7
  2100.         number = 5 * (180 / 3 + 9 ) * ( 5 - 2)
  2101.         number = number - 1
  2102.         number = number % 2
  2103.  
  2104.  
  2105. PRECEDENCE.
  2106.  
  2107. Division and multiplication have precedence over addition and subtraction.
  2108. This rule is also observed by the C compiler. Therefore, the expression 
  2109. 2 + 6 * 7 needs no parenthesis to achieve the correct result. The modulo
  2110. operator has precedence equal to division and therefore precedence over
  2111. addition and subtraction. Example:
  2112.  
  2113.         5 % 3 = 2 since 5/3 = 1 and remainder is 2.
  2114.  
  2115. Simple calculations don't need to use a variable. The following program
  2116. will illustrate:
  2117.  
  2118.         void main()
  2119.         {
  2120.           int number;
  2121.           number = 3 * 12;
  2122.           printf("Result : %d\n",number);
  2123.         }
  2124.  
  2125.                                 PAGE 61
  2126.  
  2127. --------------------------------------------------------------------------
  2128.  
  2129.  
  2130. A variable does not have to be used in the program since the %d characters
  2131. tell printf that it can expect an integer value. The term 3 * 21 can be
  2132. passed directly to the function as a parameter. The calculation of the
  2133. result occurs before the result is passed so no variable is required. The
  2134. following program is faster and shorter:
  2135.  
  2136.         main()
  2137.           {
  2138.              printf("Result: %d\n",3*12);
  2139.           }
  2140.  
  2141. An integer number can only contain a whole number, so the statement 3 / 2
  2142. places a value of one in the variable NUMBER. The correct result would have
  2143. been 1.5, but the result will be rounded to the next whole number.
  2144.  
  2145. NOTE :-
  2146.  
  2147. The number -2.25 is rounded to -2 and not -3 since -2 is larger than -3.
  2148. Lattice C rounds numbers toward 0 but this can differ with other C
  2149. compilers. Only a text run helps to explain what happens to -5 / 2 in which
  2150. either -2 (toward zero) or -3 (rounded) appears as a result.
  2151.  
  2152.  
  2153.  
  2154.                                 PAGE 62
  2155.  
  2156. ==========================================================================
  2157.  
  2158.                      CHAPTER 7 - CALCULATING IN C
  2159.  
  2160. You have already seen how fast the Amiga computes; addition(+),
  2161. subtraction(-), multiplication(*) and division(/) are familiar to you.
  2162.  
  2163. The modulo operator (%) performs another mathematical operation - modulo
  2164. division, which calculates the remainder of an integer division. THe result
  2165. is assigned to a variable using the equal sign, where the variable must be
  2166. to the left of the assignment operator. The general format is as follows:
  2167.  
  2168.         variable = operand1 <> operand2
  2169.         (<> represents the operator)
  2170.  
  2171. Frist the program calculates the expression to the right of the equal sign
  2172. and places the result in the variable to the left of the equal sign.
  2173. Because of this statements such as the following are possible:
  2174.  
  2175.         variable = variable + 1;
  2176.  
  2177. The expression is impossible in normal math, but poses no problem for the
  2178. computer. The computer reads the variable content, adds one and stores the
  2179. result in the same variable. Combinations of math operators are possible as
  2180. the following examples show:
  2181.  
  2182.         number = 3 * 32
  2183.         number = 2 + 6 * 7
  2184.         number = 5 * (180 / 3 + 9 ) * ( 5 - 2)
  2185.         number = number - 1
  2186.         number = number % 2
  2187.  
  2188.  
  2189. PRECEDENCE.
  2190.  
  2191. Division and multiplication have precedence over addition and subtraction.
  2192. This rule is also observed by the C compiler. Therefore, the expression 
  2193. 2 + 6 * 7 needs no parenthesis to achieve the correct result. The modulo
  2194. operator has precedence equal to division and therefore precedence over
  2195. addition and subtraction. Example:
  2196.  
  2197.         5 % 3 = 2 since 5/3 = 1 and remainder is 2.
  2198.  
  2199. Simple calculations don't need to use a variable. The following program
  2200. will illustrate:
  2201.  
  2202.         void main()
  2203.         {
  2204.           int number;
  2205.           number = 3 * 12;
  2206.           printf("Result : %d\n",number);
  2207.         }
  2208.  
  2209.                                 PAGE 61
  2210.  
  2211. --------------------------------------------------------------------------
  2212.  
  2213.  
  2214. A variable does not have to be used in the program since the %d characters
  2215. tell printf that it can expect an integer value. The term 3 * 21 can be
  2216. passed directly to the function as a parameter. The calculation of the
  2217. result occurs before the result is passed so no variable is required. The
  2218. following program is faster and shorter:
  2219.  
  2220.         main()
  2221.           {
  2222.              printf("Result: %d\n",3*12);
  2223.           }
  2224.  
  2225. An integer number can only contain a whole number, so the statement 3 / 2
  2226. places a value of one in the variable NUMBER. The correct result would have
  2227. been 1.5, but the result will be rounded to the next whole number.
  2228.  
  2229. NOTE :-
  2230.  
  2231. The number -2.25 is rounded to -2 and not -3 since -2 is larger than -3.
  2232. Lattice C rounds numbers toward 0 but this can differ with other C
  2233. compilers. Only a text run helps to explain what happens to -5 / 2 in which
  2234. either -2 (toward zero) or -3 (rounded) appears as a result.
  2235.  
  2236.  
  2237.  
  2238.                                 PAGE 62
  2239.  
  2240. ==========================================================================
  2241.  
  2242.                         CHAPTER 8 - VARIABLES.
  2243.  
  2244. The earlier chapters used variables. These are areas of memory used for
  2245. storing mathematical results, as well as different kinds of data.
  2246.  
  2247. Variables are subject to certain rules and regulations. They must be
  2248. assigned specific data types and unique names. As you'll see in this
  2249. chapter, there are many types, and the names can be almost anything you
  2250. want them to be.
  2251.  
  2252.  
  2253. 8.1 VARIABLE NAMES.
  2254.  
  2255. The names given to variables must follow some rules. The following is a
  2256. list which describes these rules:
  2257.  
  2258. 1.) The first character must be a letter (the underscore _ counts as a 
  2259.     letter.  After the first character any legal character can be used.
  2260.  
  2261. 2.) Characters within variable names can be letters, numbers or 
  2262.     underscore characters (the shifted minus sign).
  2263.  
  2264. 3.) No control characters or foreign characters allowed.
  2265.  
  2266. 4.) Variable names can be of any length, but many C language compilers
  2267.     only use the first 8 characters of the variable name.
  2268.     (The Lattice C compilers permits up to 30 characters, Aztec up to 31.)
  2269.  
  2270. 5.) Reserved C keywords may not be used as variable names.
  2271.  
  2272. 6.) Variable names are case sensitive. (i.e. The compiler sees a 
  2273.     difference between upper and lowercase).
  2274.  
  2275. Some examples are shown to make these rules more understandable. Some are
  2276. correct some aren't. Can you find the bad ones?
  2277.  
  2278.                                 PAGE 65
  2279.  
  2280. --------------------------------------------------------------------------
  2281.  
  2282.   
  2283.  
  2284.         a - Number_1
  2285.         b - 2_pi
  2286.         c - first-var
  2287.         d - Book_No_1
  2288.         e - Book_No_2
  2289.         f - int
  2290.         g - _flag
  2291.         h - int_valu
  2292.         i - number_1
  2293.         j - secret_password
  2294.  
  2295. The following variable names are correct: a), d), e), g), h), i) and j). It
  2296. should be noted that a) and i) are different values since upper and lower
  2297. case letters are differentiated. d) and e) may refer to the same value on
  2298. some C compilers, since the names are the same for the first 8 letters.
  2299. Errors would occur on some C compilers since these variable names are
  2300. longer than eight characters: c), d), e) and j). h) uses a C keyword as a
  2301. variable name, but this is permitted since the rest of it doesn't match the
  2302. keyword.
  2303.  
  2304. Look at examples b), c) and f). The variable in b) starts with a number
  2305. (not allowed). A hyphen appears in c) (the hyphen is considered a special
  2306. character). Finally f) uses a variable name which is a reserved keyword of
  2307. C.
  2308.  
  2309. The following list shows the reserved words used in C:
  2310.  
  2311.         auto            enum            short
  2312.         break           extern          sizeof
  2313.         case            float           static
  2314.         char            for             struct
  2315.         continue        goto            switch
  2316.         default         if              typedef
  2317.         do              int             union
  2318.         double          long            unsigned
  2319.         else            register        void
  2320.         entry           return          while
  2321.  
  2322.  
  2323.  
  2324.  
  2325.                                 PAGE 66
  2326.  
  2327. --------------------------------------------------------------------------
  2328.  
  2329. 8.2  DATA TYPES.
  2330.  
  2331. Until now three data types have been described: INT, FLOAT and CHAR
  2332. (strings).
  2333.  
  2334. INT :
  2335.  
  2336. Integer values are type INT. The 16-bit INT type represents whole numbers
  2337. between -32768 and +32767. The INT type works well for general use. The
  2338. Amiga libraries use 32-bit integers, but for portability of your source
  2339. code to other computers you may want to use 16-bit integers.
  2340.  
  2341.  
  2342. FLOAT:
  2343.  
  2344. Floating point numbers are assigned the data type FLOAT. A FLOAT variable
  2345. can store extremely large or small numbers, and numbers with decimal
  2346. places. In this type of variable the value can be represented in scientific
  2347. notation. Very small numbers such as 0.000000015 can be written as 15E-7
  2348. (the use of E is an abbreviation). 15E-7 is scientific notation for:
  2349.  
  2350.         15 * 10 (to the power of) -7 
  2351.         
  2352. Numbers with as many as 15 places can be written. The "e" which separates
  2353. the exponent (here-7) from the mantissa (in this case 15), can be written
  2354. in upper or lowercase letters. In both cases the compiler will translate it
  2355. without problems.
  2356.  
  2357. Even the FLOAT variable type has it's limitations. The largest number
  2358. permitted is 10**38. Any number less than 10**-38 converts to a 0. The
  2359. value 10**-40 when written out is a number which has a decimal point, 39
  2360. zeros and a one, in that order. The computer views it as 0. Floating point
  2361. variable remain accurate up to seven decimal places. Try the MATH.C program
  2362. from section 4.5.5; enter the number 16.8. The program converts the number
  2363. to 16.799999.
  2364.  
  2365.  
  2366. DOUBLE:
  2367.  
  2368. If you need more accuracy use the DOUBLE variable type. Variable of type
  2369. DOUBLE are about twice as accurate (11-14 decimal places). However, DOUBLE
  2370. variable require more memory.
  2371.  
  2372. There are times when FLOAT and DOUBLE variables don't have the accuracy of
  2373. integer values. On the other hand, rounding numbers off can cause incorrect
  2374. results in multiple calculations. The result becomes more inaccurate with
  2375. every additional operation.
  2376.  
  2377. Avoid comparing a fixed value during a test. For example:
  2378.  
  2379.         if(value==1.0)    /* not like this */
  2380.  
  2381.                                 PAGE 67
  2382.  
  2383. --------------------------------------------------------------------------
  2384.  
  2385.  
  2386.  
  2387. It would be better to test if it is larger or smaller so that the value
  2388. tested is not skipped through a rounding error. Otherwise an infinite loop
  2389. could result.
  2390.  
  2391. Special conditions must be considered when using floating point numbers. To
  2392. determine if a constant without fractions following the decimal point (for
  2393. example 2) is a floating point number another digit must be added after the
  2394. decimal point. This error occurs during the PRINTF call in the following
  2395. example:
  2396.  
  2397.         printf("Result of 2 / 3 = %f.\n", 2/3);
  2398.  
  2399. The example computes 2/3 as an integer value and passes 0 as a result. The
  2400. function waits for a floating point number which was indicated by %f. The
  2401. example below is the correct version
  2402.  
  2403.         printf("Result of 2 / 3 = %f.\n",2.0/3.0);
  2404.  
  2405.  
  2406. NOTE:
  2407.  
  2408. You may crash the system as well as get the wrong answer with the example
  2409. above. If you want to try to two examples above, save any important data
  2410. that you might have in RAM disk to a floppy disk before continuing.
  2411.  
  2412. CHAR:
  2413.  
  2414. Other data types can be derived from the basic types INT and FLOAT. For
  2415. example, the type char which can accept a character is really a variable
  2416. for whole numbers between -128 and 127. This small relative of INT
  2417. respresents the ASCII values of the characters.
  2418.  
  2419. LONG:
  2420.  
  2421. The LONG type is another type derived from INT. Long accepts integers
  2422. between -2,147,483,648 and 2,147,483,647. If you must define contants as
  2423. long values, place an l or L behind the floating point number instead of
  2424. .0. For example:
  2425.  
  2426.         1l
  2427.  
  2428. SHORT:
  2429.  
  2430. The C keywords UNSIGNED and SHORT can be used a adjectives to the basic
  2431. types. These specify integer values. The combinations of unsigned and short
  2432. cannot be used with FLOAT values. UNSIGNED defines an integer number which
  2433. has no sign; SHORT accepts only 16-bit numbers.
  2434.  
  2435. If the indication of INT or FLOAT is missing, C defaults to INT. The
  2436. following combinations are valid:
  2437.  
  2438.         unsigned = unsigned int
  2439.         short = short int = [compiler dependant] char
  2440.         long = long int
  2441.         unsigned long int
  2442.         long float = double
  2443.  
  2444.                                 PAGE 68
  2445.  
  2446.  
  2447.  
  2448. The advantage of UNSIGNED is limited to positive values and extends the
  2449. limit of the normal type. For example, UNSIGNED INT, accepts numbers
  2450. between 0 and 65535 . The normal INT type only allows positive values up to
  2451. 32767. Unsigned numbers also allow operations which cannot be performed
  2452. with other data types. More on this later.
  2453.  
  2454. The value assignments to CHAR variables proceeds in the following manner,
  2455. as in INT values;
  2456.  
  2457.         char character;
  2458.         char = 65;
  2459.  
  2460. ChAR stores characters. This is done with the following assignment which
  2461. leads to the same result as the line above.
  2462.         
  2463.         character = 'a';
  2464.  
  2465. The combination of integer value with the attributes SHORT, LONG and
  2466. UNSIGNED returns different results from one compiler to another. For this
  2467. reason no general value or memory reuqirement can be provided. The
  2468. following relaionship exists between the length of variables used by all C
  2469. compilers.
  2470.  
  2471.         char <= short <= int <= long.
  2472.  
  2473. The table below describes the length of the different numeric variable
  2474. types.
  2475.  
  2476.                 Lattice         Aztec.
  2477.  
  2478. char            1 byte          1 byte
  2479. short           2 bytes         2 bytes
  2480. int             4 bytes         2 bytes
  2481. long            4 bytes         4 bytes
  2482.  
  2483.  
  2484.                                 PAGE 69
  2485.  
  2486. --------------------------------------------------------------------------
  2487.  
  2488. 8.3 TYPE CONVERSION.
  2489.  
  2490. Type conversion sometimes becomes necessary during computation because of
  2491. the use of various data types. The following rules govern type conversion;
  2492.  
  2493. 1.)     CHAR and SHORT always convert to INT; FLOAT always converts to
  2494.         DOUBLE.
  2495.  
  2496. 2.)     If, after these conversions, one of the operators should have the
  2497.         type DOUBLE, the second operand and the result also convert to 
  2498.         DOUBLE.
  2499.  
  2500. 3.)     If a data type is now LONG, all participating values also convert
  2501.         to LONG.
  2502.  
  2503. 4.)     If an UNSIGNED value exists among the operands, all values convert
  2504.         to UNSIGNED.
  2505.  
  2506.  
  2507.                                 PAGE 70
  2508.  
  2509. --------------------------------------------------------------------------
  2510.  
  2511. 8.4 THE CAST OPERATOR.
  2512.  
  2513. Constants, function values and variables can be converted into a specific
  2514. data type. The parameter to be converted is placed in parenthesis and is
  2515. preceeded by a data type in parenthesis. This is the CAST operator. The
  2516. parenthesis are not always required, but are recommended because of the
  2517. high precedence of the type conversion. For example;
  2518.  
  2519.         LONG number;
  2520.         number = 123 / (long)('a' / 1.5);
  2521.  
  2522. In a general format, the expression is:
  2523.  
  2524.         type (parameter)
  2525.  
  2526. Any data type can be substituted for the word TYPE.
  2527.  
  2528.                                 PAGE 71
  2529.  
  2530. ==========================================================================
  2531.         
  2532.                         CHAPTER 9 - PRINTF AND SCANF.
  2533.         
  2534. The most powerful output function in C is PRINTF. Youve seen a little of
  2535. what it can do with screen output using the examples printed earlier in
  2536. this book.
  2537.  
  2538. The SCANF function gives the user the option of input to the computer. You
  2539. have had a chance to work with this option also.
  2540.  
  2541. Both SCANF and PRINTF use a number of format specifications and escape
  2542. sequences for controlling the format and type of input and output.
  2543.  
  2544.  
  2545. 9.1  MORE ESCAPE SEQEUNCES.
  2546.  
  2547.  
  2548. You'll remember reading about the \n escape seqeunce in chapter 3. The
  2549. following list shows other escape sequences, which youll find useful for
  2550. controlling text output.
  2551.  
  2552. \t      places output at next tab stop.
  2553. \b      moves current write position one place to the left.
  2554. \r      inserts carriage return at first position of the current line.
  2555. \n      inserts carriage return and linefeed.
  2556. \f      inserts form feed.
  2557. \\      prints the backslash character.
  2558. \"      prints quotation mark within the string.
  2559. \'      prints apostrophe within the string.
  2560. \nn     prints any character with the octal value NN.
  2561.  
  2562. NOTE :- An escape sequence uses two characters in the text, but represents
  2563. only one character. Keep this in mind when calculating memory usage.
  2564.  
  2565.  
  2566. The following program uses the \t escape sequence for tab stops:
  2567.  
  2568.         main()
  2569.           {
  2570.                 printf("An\tExample,\ttwo,\ttabs,\tspacing");
  2571.                 printf("\tSpacing\tText!\n");
  2572.            }
  2573.  
  2574. For our next assignment we wish to display the following text :
  2575.  
  2576.         Use the control characters : "\n", "\t"!
  2577.  
  2578.  
  2579.                         PAGE 75
  2580.  
  2581. --------------------------------------------------------------------------
  2582.  
  2583. It is not possible to simply place the text in quotation marks since they
  2584. already occur in the text. Escape sequences are necessary. The program
  2585. prints the quotation mark using the \" escape sequence, the backslash with
  2586. \\. The necessary PrintF call appears as follows:
  2587.  
  2588.         printf("Use the Control Characters : \"\\n\",\"\\t\"!");
  2589.  
  2590. Here is an example Program :
  2591.  
  2592.         main()
  2593.            {
  2594.                 printf("small");
  2595.                 printf"\"T e s t  P r o g r a m ");
  2596.                 printf("\"\n\nWhere\nis the \ntext now?\n");
  2597.                 printf("\t Everything OK ? \n");
  2598.            }
  2599.  
  2600. The output is :
  2601.  
  2602. Small "T e s t  P r o g r a m "
  2603. Where
  2604. is the 
  2605. text now?
  2606.         Everything OK ?
  2607.  
  2608.  
  2609.                         PAGE 76
  2610.                         
  2611. -------------------------------------------------------------------------
  2612.  
  2613. 9.2  FORMAT SPECIFICATION.
  2614.  
  2615. Strings can accomodate format specifications as well as text and escape
  2616. sequences. Every format specification has a corresponding varaible attached
  2617. to the string and separated from the string by a comma. The format
  2618. specification always starts with a percent character (%) and can be used in
  2619. the printf and scanf functions.
  2620.  
  2621. A difference from the format string of the printf function is important.
  2622. The scanf function reads in data. For this reason the escape sequences \n
  2623. (linefeed), \t (tab) and space divide the input into separate fields.
  2624.  
  2625. Here is a table with format specifications for printf and scanf:
  2626.  
  2627.  
  2628. Format Specification    Data Type.
  2629. --------------------    ---------------------------------------- 
  2630.  
  2631. %c                      Char (one character)
  2632. %d                      integer value.
  2633. %s                      string. 
  2634. %f                      Float and double.
  2635. %o                      Integer value as octal (base 8)
  2636. %x                      Integer value as hex (base 16)
  2637. %u                      Unsigned integer value (printf only)
  2638. %e                      Float or Double (printf only) in scientific 
  2639.                         notation.
  2640. %g                      shortest form of %e and %f (printf only)
  2641. %h                      short (scanf only)
  2642. %%                      represents the % character (printf only).
  2643.  
  2644. ADDITIONS :-
  2645.  
  2646. The integer elements d,u,o and x can be preceeded by the letter 1 to
  2647. indicate that long values instead of integers are used. Long values are
  2648. integers of double length. An L preceeding floating point numbers
  2649. containing e,f and g indicates that double values are expected. The field
  2650. width of the input or output of a field can also be indicated with a format
  2651. element. After the percent sign, the size of the individual field can be
  2652. indicated. If the first character of this number is a minus sign , the text
  2653. is left justified. Spaces fill the remaining positions in the field.
  2654.  
  2655. Without indication of the field width, the standard setting for %f in the
  2656. printf function is %.6f. The output therefore always has six decimal places
  2657. and any field size.
  2658.  
  2659. PRINTF and and elements for FLOAT values:
  2660.  
  2661.  
  2662. %<min>.<fraction>F
  2663.  
  2664.  
  2665.                                 PAGE 77
  2666.  
  2667. -------------------------------------------------------------------------
  2668.  
  2669.  
  2670. <min> indicates the minimum width of the output field. <fraction> is the
  2671. maximum number of numbers after the decimal point. F is one of the format
  2672. specifications e,f or g. The indication of 0 for fractional positions
  2673. truncates all numbers after the decimal point (e.g., %.0f). For example :
  2674.  
  2675.         printf("Number %5.21f\n", 12.345);
  2676.  
  2677. creates the output:
  2678.  
  2679.         Number 12.35
  2680.  
  2681. In this case the program expects a DOUBLE number (1f) at least 5 characters
  2682. wide, but with only two decimal places. Since rounding is performed to the
  2683. second number after the decimal point, the number 5 appears at the last
  2684. position. If less numbers are available than the number indicated for the
  2685. positions after the decimal point, zeros are attached.
  2686.  
  2687. Printf and elements for integers:
  2688.  
  2689.         %<min>F
  2690.  
  2691. <min> indicates the minimum width of the output field. F represents one of
  2692. the format instructions d,u,o or x. Example :
  2693.  
  2694.         printf(">%4d<",12);
  2695.  
  2696. Output :
  2697.  
  2698.         > 12<
  2699.  
  2700. printf & %s:
  2701.  
  2702.         %<min><real>s
  2703.  
  2704. <min> indicates the minimum width of the output field, while <real>
  2705. describes the actual number of characters displayed. The following examples
  2706. show the effects on the string "SampleText":
  2707.  
  2708. Format Specification            Output
  2709. --------------------            -------------------------------
  2710. >%6s<                           >sampletext<
  2711. >%-6s<                          >sampletext<
  2712. >%12s<                          >      sampletext<
  2713. >%-12s<                         >sampletext      <
  2714. >%12.6s<                        >      sample<
  2715. >%-12.6s<                       >sample      <
  2716. >%.6s<                          >sample<
  2717.  
  2718. The SCANF function is much simpler. Only one number exists which indicates
  2719. the maximum input length possible. As soon as a character no longer fits
  2720. into the format of a data type, or a control or balnk character appears,
  2721. the input for the current field ends. This means that during input only
  2722. characters representing an integer number are used.
  2723.  
  2724.                                 PAGE 78
  2725.  
  2726. -----------------------------------------------------------------------------
  2727.  
  2728. If other characters are input, the integer number input ends. In addition
  2729. "*" can be used which preceeds the instruction for data type and suppresses
  2730. the assignment. The field is simply skipped in this case.
  2731.  
  2732.         int i;
  2733.         float f;
  2734.         char string[50];
  2735.         scanf("%3d %f %*d %s", &i, &f, string);
  2736.         Input : 1234567.89 12345all clear?
  2737.  
  2738. Value Assignment :
  2739.  
  2740. i contains 123 since the field should have 3 places and only numbers can
  2741. appear. The value 4567.89 is in f, because the space after "9" prevents
  2742. additional reading of input. The same happens after the storage of "all"
  2743. in the string[]. The number sequence 12345. which normally is assigned to
  2744. an integer value, was skipped because of the asterisk. The means that with
  2745. the SCANF no spaces can be read. This makes SCANF less than ideal for
  2746. string input.
  2747.  
  2748. If the reader cant remember all of this material, dont worry. It is used
  2749. intensively during the course of the format specifications.
  2750.  
  2751.                                 PAGE 79
  2752.  
  2753. -----------------------------------------------------------------------------
  2754.  
  2755. 9.3 OCTAL AND HECADECIMAL.
  2756.  
  2757. Two number systems are often used in C. To discuss these systems well start
  2758. by looking at the decimal system. Lets take a decimal number and disect it
  2759. into its component parts :-
  2760.  
  2761. 5279 = 
  2762.         = 5000  + 200   + 70    +9
  2763.         = 5*1000+ 2*100 + 7*10  +9
  2764.         = 5* 10**3 + 2 * 10**2 + 7 * 10**2 + 9 * 10**0
  2765.  
  2766. This make the origin of the term decimal = 10 in our number system clear.
  2767. Every number position has a certain value. There are ones, tens, hundreds
  2768. etc.. The value of these positions is multiplied with the number at that
  2769. location. For example 7 * 10. The factors 1, 10, 100, 1000 can be traced
  2770. again to the base 10. The exponent in the base 10 depends on the position
  2771. of the digit in the number. The first position corresponds to exponent 0,
  2772. the second exponent 1, the third 2 and so on..
  2773.  
  2774. Numbers between 0 to 9 can be used, which makes 10 different numbers
  2775. available. This is the reason the system is called base 10.
  2776.  
  2777.  
  2778. OCTAL SYSTEM :
  2779.  
  2780. If you used 8 different numbers (0-7) instead of ten the base in the
  2781. calculation would be 8. This base 8 system is better known as the octal
  2782. system. The follwing example shows the process of calculation of a number
  2783. in the octal system. To differentiate the number systems, the base number
  2784. appears in parenthesis following the number:
  2785.  
  2786.         6204
  2787.  
  2788.         = 6 * 8**3 + 2 * 8**2 + 0 * 8**1 + 4 * 8**0
  2789.         = 6 * 512  + 2 * 64   + 0 * 8    + 4 * 1
  2790.         = 3072     + 128      + 0        + 4
  2791.         = 3204 (10)
  2792.  
  2793. This brings us back to format specifications. To write a variable in octal
  2794. on the screen use %o.
  2795.  
  2796.         printf("3204 dec = %o octal\n",3204);
  2797.  
  2798.                                 PAGE 80
  2799.  
  2800. ----------------------------------------------------------------------------
  2801.  
  2802. HEXADECIMAL
  2803.  
  2804. The format specification %x converts a number into the hexadecimal system.
  2805. As the name suggests, hexadecimal is base 16. This produces a small
  2806. problem. The decimal system uses numbers (0-9), but hexadecimal system need
  2807. 16. Hexadecimal uses the first 6 numbers of the alphabet as the top six
  2808. numbers. The letter A represents the number 10; B has the value 11; C 12; D
  2809. 13; E 14 and F 15. The following hexadecimal number can be converted as
  2810. follows:
  2811.  
  2812.         5DA9
  2813.  
  2814.         = 5 * 16**3     + 13 * 16**2    + 10 * 16**1    + 9 * 16**0
  2815.         = 5 * 4096      + 13 * 256      + 10 * 16       + 9 * 1
  2816.         = 20,480        + 3,328         + 160           + 9
  2817.         = 23,997 (10).
  2818.  
  2819. Hexadecimal and octal numbers can be used in C exactly like decimal
  2820. numbers. Hex numbers use the format specification 0X to indicate that they
  2821. are base 16. For the octal system only a leading zero is required. Some
  2822. examples :
  2823.  
  2824.         0x5DA9
  2825.         0xFFFF
  2826.         0612
  2827.         0x5da9
  2828.         0x123
  2829.         0815
  2830.         0X5da9
  2831.         06543
  2832.  
  2833. One of the above combinations is wrong. Example the numbers again
  2834. carefully. The error is hidden in the innocent number combination 0815.
  2835. With the leading zero it should represent an octal number. There is no
  2836. digit with the value 8 in the octal system.
  2837.  
  2838. The response depends on the compiler. The compiler can issue a message that
  2839. a wrong number was entered, or accept it as a decimal number. The lattice C
  2840. compiler converts the number from octal into decimal notation. This
  2841. produces something entirely different, namely 525(10) which is equal to
  2842. 1015(8).
  2843.  
  2844. The user would soon get tired of entering every number for conversion. A
  2845. good C implementation does that for you.
  2846.  
  2847. To write a program to convert numbers from various bases into the decimal
  2848. system the procedure must differ slightly. Nothing is simpler than
  2849. constructing a loop to save typing time. Starting with the last position
  2850. ( 9 in the example), multiply it with the value of the position. The value
  2851. at the last position is then 9 * 1 = 9. The next position has the value 16
  2852. , and the variable containing this value with the base (16). The next
  2853. position is therefore 10 * 16 = 160.
  2854.  
  2855.  
  2856.                                 PAGE 81
  2857.  
  2858. --------------------------------------------------------------------------
  2859.  
  2860. All computed intermediate results are added in a separate sum. This is the
  2861. same path as the manual procedure with the exception that every step again
  2862. is divided into smaller steps. The user doesnt have to understand how the
  2863. calculation works, since you are trying to learn C and not mathematics.
  2864.  
  2865.  
  2866. 9.3.1 CONVERSION PROGRAM.
  2867.  
  2868. Analyse the following listing in the basis of the explanations already
  2869. provided. If it isnt clear a few PRINTF functions inserted in the program
  2870. could print out the current value of one or more variables. This makes the
  2871. most important variables visible.
  2872.  
  2873.         /* base-con.c 9.3.1                             */
  2874.         viod main()
  2875.         {
  2876.            long base,collect,value;
  2877.            int index,help;
  2878.            char test[100];
  2879.  
  2880.         printf("Please input Base of numbering system!\n");
  2881.         scanf("%ld", &base);
  2882.         printf("Input number for conversion in base %ld system!\n",base);
  2883.         scanf("%80s",test);
  2884.         collect = 0;
  2885.         value = 1;
  2886.         index = strlen(test) - 1; /* new function */
  2887.         while (index >= 0)
  2888.            {
  2889.                 help = test[index];
  2890.                 if(help >= 'a') /* lowercase letter */
  2891.                   help = help - 'a' + 10;
  2892.                 else
  2893.                   if (help >= 'A')      /* upper case letter */
  2894.                     help = help - 'A' + 10;
  2895.                   else  /* probably a number    */
  2896.                     help = help - '0';
  2897.                 
  2898.                 collect = collect + value * help;
  2899.                 index = index - 1;
  2900.                 value = value * base;
  2901.             }
  2902.         printf("%s(%ld) = %ld(10)\n", test, base, collect);
  2903.         }
  2904.  
  2905. The program uses the LONG data type a lot. This can also be noted in the
  2906. format specification %ld for the input and output of these variables. The
  2907. scanf function which reads a number as a string has something new. After
  2908. the percent sign appears an 80, followed by the format specification %s for
  2909. string. This value between the percent sign and the format specification
  2910. tells the function the maximum number of characters permitted.
  2911.  
  2912.                                 PAGE 82
  2913.  
  2914.  
  2915. ---------------------------------------------------------------------------
  2916.  
  2917. In this case the string cannot be longer than 80 characters (+1 end of line
  2918. = 81). In reality this does not work out quite that way. As a maximum only
  2919. 80 characters are processed, but the user can write several lines. Only the
  2920. first 80 characters are used.
  2921.  
  2922. The indication if a maximum number of places is also permitted for other
  2923. data types (see the example in SCANF). A new function STRLEN will be
  2924. introduced next. It delivers the characters in a string. The concluding
  2925. zero byte is not included. The result is assigned with an equal sign. The
  2926. only parameter required by STRLEN is the string to be investigated. One of
  2927. the examples already calculated the length of the string. The strlen
  2928. function is therfore not very large.
  2929.  
  2930. In the following WHILE loop the string which was input is processed. To
  2931. avoid the use of the expression test[index] for every calculation, the
  2932. character at that location is copied into the variable HELP. The user
  2933. should have noticed that help was defined as an integer variable. Yet an
  2934. attempt is made to store a character at that location. Computers view
  2935. characters as numbers. Every letter has a numeric code, just like a number.
  2936. The CHAR variables are nothing more than small integer memory areas which,
  2937. depending on the compiler, accept a value between -128 to 127, or , from 0
  2938. to 255. These peculiarities of calculating numbers with characters and
  2939. their codes will be discussed later.
  2940.  
  2941.                                 PAGE 83
  2942.  
  2943. ---------------------------------------------------------------------------
  2944.  
  2945. 9.4 CHARACTER CODES.
  2946.  
  2947. After the character was made available in HELP, it is tested to see wether
  2948. it was an uppercase or lowercase letter. These can be used as auxillary
  2949. numbers in a system whose base is 10. In the haxadecimal systems the
  2950. letters A-F are used. When it has been determined what type of character
  2951. (uppercase, lowercase or number)is available its actual value is
  2952. calculated. 9 is not 9 here. Confused ? You remember how a character was
  2953. assigned to the CHAR variable:
  2954.  
  2955.         character = '9';
  2956.  
  2957. The 9 is a character which represents the number 9. This character also has
  2958. a special ASCII character code. This ASCII code for the number 9 is the
  2959. value 57. The assignment that follows gives the same result as the example
  2960. above :
  2961.  
  2962.         character = 57;
  2963.  
  2964. Caclulation with the variable requires the value 9 and not the stored code
  2965. 57. First subtract 48 from 57 (48 is the character code for 0). This is
  2966. practical since all numbers are in sequential order with the following
  2967. codes :
  2968.  
  2969.         CODE                    CHARACTER
  2970.         ----------              ----------
  2971.  
  2972.         48                      0       
  2973.         49                      1
  2974.         50                      2
  2975.         51                      3
  2976.         ..                      ..      
  2977.         ..                      ..
  2978.         57                      9
  2979.  
  2980. The letters of the alphabet also follow this order. The table starts with A
  2981. (code 65), B (code 66) etc.. The lowercase letters are in a separate list.
  2982. The first value there is 97 for 'a'. Lets look at a program section :
  2983.  
  2984.         char test;
  2985.  
  2986.         test = 'B';
  2987.         test = test - 'A' + 10;
  2988.  
  2989. What is contained in the value TEST after the execution of this sequence ?
  2990. An equivalent part appears in the conversion program. The right result is
  2991. 11. In the last line, test contains the letter B with the value 66.
  2992. Subtracting A from this results in 1; plus 10 is 11. That is the value that
  2993. the letter B represents in the hexadecimal system.
  2994.  
  2995.                                 PAGE 84
  2996.  
  2997. ---------------------------------------------------------------------------
  2998.  
  2999. The following line converts an uppercase letter into a lowercase letter :
  3000.  
  3001.         test = test - 'A' + 'a';
  3002.  
  3003. That is much more readable than :
  3004.  
  3005.         test = test - 65 + 97;
  3006.  
  3007. or
  3008.  
  3009.         test = test + 32;
  3010.  
  3011. The codes are nearly identical on almost all computers thanks to the ASCII
  3012. standard. ASCII assigns a specific code to each character.
  3013.  
  3014. To obtain an overview of the ASCII codes, the program below displays every
  3015. code and its character (32-127, 160-255). The codes 0-31 and 128-159 were
  3016. left out because they either have special functions (e.g. 13 is equal to
  3017. \n) or do not produce anything on the screen.
  3018.  
  3019.         /* ASCII.c 9.4                  */
  3020.         main()
  3021.         {
  3022.           int i;
  3023.           printf("\n\n");
  3024.           for(i=32; i<=127; i = i + 1)
  3025.              printf("\t%-3d %c",i,i);
  3026.           for(i=160; i<=255; i = i + 1)
  3027.              printf("%-3d %c",i ,i);
  3028.           printf("\n");
  3029.         }
  3030.  
  3031. These are all of the characters that can be printed with the PRINTF
  3032. function.
  3033.  
  3034. 9.4.1 ABOUT THE BACKSLASH.
  3035.  
  3036. Output using a character code displays a character which cannot be accessed
  3037. with the keyboard or with the backslash. The backslash must preceed the
  3038. code. The compiler replaces the combination of backslash and the individual
  3039. digits of the code with a single character. One hitch - the number must be
  3040. entered in octal notation instead of decimal notation. The following
  3041. command displays the +/- character (character code 177):
  3042.  
  3043.         printf("\261");
  3044.  
  3045. The number 177 decimal corresponds to 261 octal. The conversion can be
  3046. avoided using a format specification as shown below:
  3047.  
  3048.                                 PAGE 85
  3049.  
  3050. ---------------------------------------------------------------------------
  3051.  
  3052.         printf("%c", 177);
  3053.  
  3054. This character is not used directly in the string, but goes directly to the
  3055. printf function in the form of a character code, with the %c.
  3056.  
  3057.         printf("The result is \261.\n");
  3058.         printf("The result is %c.\n", 177);
  3059.  
  3060. The control character %c permits the output of a single character by
  3061. indicating the character code, even if an integer value was passed.
  3062.  
  3063.  
  3064. 9.4.2 GOING THE OTHER DIRECTION.
  3065.  
  3066. The following program converts decimal numbers into octal numbers. It is
  3067. almost the reverse of the previous conversion program which converted
  3068. numbers into the decimal system.
  3069.  
  3070.         /* dec_conv.c   9.4.2           */
  3071.         void main()
  3072.         {
  3073.           long base,test,help,rest;
  3074.           int index;
  3075.           char result[260];
  3076.  
  3077.           printf("Please input number Base!\n");
  3078.           scanf("%ld",&base);
  3079.           printf("Input number in decimal system!");
  3080.           scanf("%ld", &test);
  3081.           index = 0;
  3082.           for (rest = test, rest >= 0; rest = rest / base)
  3083.              {
  3084.                 help = rest % base; /* remainder of division */
  3085.                 if(help > 9)
  3086.                    result[index] = help + 'A' - 10;
  3087.                 else
  3088.                    result[index] = help + '0';
  3089.                 index = index + 1;
  3090.               }
  3091.  
  3092.           printf("%ld(10) = ",test);
  3093.           index = index - 1; /* last entry is still unused. */
  3094.           while(index>=0)
  3095.              {
  3096.                 printf("%c",resut[index]);
  3097.                 index = index - 1;
  3098.               }
  3099.            printf("(%ld)\n"), base);
  3100.         }
  3101.  
  3102.                                 PAGE 86
  3103.  
  3104. --------------------------------------------------------------------------
  3105.  
  3106.  
  3107.  
  3108.  
  3109.  
  3110.                         CHAPTER 10 - THE PREPROCESSOR.
  3111.  
  3112. The preprocessor is part of the compiler program which first processes the
  3113. source code. It accepts source text as written. There are some special
  3114. directives which force the preprocessor to make changes in the program
  3115. source text. After the preprocessor has done its work, the part of the
  3116. compiler responsible for the translation uses this 'processed' version of
  3117. the source code text. This version can appear quite different from the
  3118. listing.
  3119.  
  3120. To differentiate the pre-processor directives from other C statements and
  3121. functions there are two important guidelines:
  3122.  
  3123.         1.) All directives begin with the # character.
  3124.         2.) All directives begin in the first column.
  3125.  
  3126.  
  3127. 10.1 DEFINE
  3128.  
  3129. Lets first consider the most important and most used preprocessor
  3130. directive; #DEFINE. #DEFINE replaces a certain character string with
  3131. another string. The preprocessor exchanges the two text strings. Lets think
  3132. about what the text replacement could be used for.
  3133.  
  3134. Assume that a constant is used during calcualtions. For example during the
  3135. calculation of a sales tax, a certain percentage (4% perhaps) appears
  3136. regularly. If this percentage is used 10 to 20 times in a program and the
  3137. sales tax percentage changes, a change in the program can become difficult.
  3138. It can also lead to errors. Perhaps a wrong value would be returned if the
  3139. number 4 appeared elsewhere in the program. An entry can be missed during
  3140. the changes. It is simpler to use the #Define directive. An application
  3141. would appear as follows:
  3142.  
  3143.         #define TAX 4
  3144.  
  3145. Up to this line the text TAX can be used which is then replaced by the
  3146. preprocessor with the text 4. Also the following line could be used :
  3147.  
  3148.         printf("TAX-rate %d",TAX);
  3149.  
  3150. The preprocessor passes to the compiler the following substitute line:
  3151.  
  3152.         printf("TAX-rate %d",4);
  3153.  
  3154.                                 PAGE 89
  3155.  
  3156. --------------------------------------------------------------------------
  3157.  
  3158. Nothing has changed within the parenthesis. This is good since it would be
  3159. impossible to output a string such as TAX on the screen. Nothing inside the
  3160. quotation marks can be touched by the preprocessor.
  3161.  
  3162. Defines are always used in a large program. The following program explains
  3163. the usage of #defines. What the program produces can be seen readily in the
  3164. listing :
  3165.  
  3166.         /* DEFINE.c 10                  */
  3167.         #define BEGIN 1
  3168.         #define END 100
  3169.         #define STEPS 2
  3170.  
  3171.         void main()
  3172.           {
  3173.                 int i;
  3174.  
  3175.                 printf("\n");
  3176.                 for(i=BEGIN; i<=END; i = i + STEPS)
  3177.                    printf("%5d", i);
  3178.                 for(i=END; i >= BEGIN;i = i - STEPS)
  3179.                    printf("%5d",i);
  3180.                 printf("\n");
  3181.            {
  3182.  
  3183. Even in a small program the DEFINE directives can enhance the readability
  3184. of a program. An example is marking the end of a string with a null byte.
  3185. This null byte is also called end of string. With the abbreviation EOS its
  3186. an often used define. The definition appears as follows :
  3187.  
  3188.                 #define EOS '\0'
  3189.  
  3190. That is more correct than simply indicating a 0. The entries of a string
  3191. are considered individual characters. It is therefore good C style to use
  3192. data type assignments. The single quote mark informs the compiler that a
  3193. single character is used. The backslash followed by the octal value
  3194. indicates the character code (see section 9.3).
  3195.  
  3196.  
  3197. The number zero in the octal system, the decimal system and any other
  3198. systems is always zero. A conversion in this case isnt difficult. Using the
  3199. character with the code zero, or the code directly (zero) in the assignment
  3200. is of no consequence.  In future programs which use strings, the definition
  3201. of EOS should appear in one of the first lines.
  3202.  
  3203. If the reader thinks that the subject of #define is now finished, he is
  3204. wrong. The many capabilities which are provided with the #define directive
  3205. will be discussed in more detail in a separate chapter.
  3206.  
  3207.                                 PAGE 90
  3208.  
  3209. --------------------------------------------------------------------------
  3210.  
  3211. 10.2 INCLUDE.
  3212.  
  3213.  
  3214. Another important preprocessor directive is #include. A file can be
  3215. combined with the source file during compilation with this directive. This
  3216. is similar to appending a file to the current file ( <esc><if> from ED) and
  3217. then saving the appended file. The compiler does not differentiate where
  3218. the definitions originated because for the compiler only one file exists.
  3219. This preprocessor directive is ideally suited to include multiple #define
  3220. directives into the program. Assume that the following #defines were stored
  3221. in a file with the name DEF_NEW.H :
  3222.  
  3223.         #define EOS '\0'
  3224.         #define MAXLEN 81
  3225.         #define EOF -1
  3226.  
  3227. If you have a source code text that uses these #define directives you dont
  3228. have to re-enter them. All you have to do is #include the file DEF_NEW.H:
  3229.  
  3230.         #include "def_new.h"
  3231.  
  3232. The file extension .H stands for header file. This ensures that all #define
  3233. directives are available throughout the listing. It is not a requirement
  3234. but should be done anyway. Although this preprocessor directive can appear
  3235. at any place in a file, it is better to include it at the head of the
  3236. source code.
  3237.  
  3238. The filename is always written between quotation marks. In this case the
  3239. compiler searches in the directory where the source code is located. You
  3240. can also enter the include file within the greater than and less than
  3241. characters:
  3242.  
  3243.         #include <def_new.h>
  3244.  
  3245.  
  3246. STDIO.H
  3247.  
  3248. The compiler assumes that the file is now located in a subdirectory in
  3249. which all .H files can be found. The path to this subdirectory passes to
  3250. the compiler during the start. There is a series of these files which are
  3251. waiting to be used. One of the most popular of these files can be found
  3252. under the name STDIO.H. This stands for STanDard Input Output Header file.
  3253. In Lattice C it is included in the include directory. This file can be
  3254. examined using the ED editor.
  3255.  
  3256.                                 PAGE 91
  3257.  
  3258. --------------------------------------------------------------------------
  3259.  
  3260.                 CHAPTER 11 - ABBREVIATIONS.
  3261.  
  3262.  
  3263. We said earlier that C is an ideal language for lazy people who don't lije
  3264. to type. This is still true since C lets you compress many functions into
  3265. smaller packages using abbreviations. This chapter describes the art of
  3266. abbreviating code in C.
  3267.  
  3268. C abbreviations help save time typing. Lets start with the simplest
  3269. abbreviations - those used in arithmetic operations. The equation below may
  3270. look fairly similar to you. Believe it or not, this can be converted to a
  3271. shortened form of the same equation:
  3272.  
  3273.         number = number * 4;
  3274.  
  3275. What could be saved here? The variable number appears twice. This doesnt
  3276. have to be so. The C language allows you to abbreviate the equation to the
  3277. point where you only need to use the variable once instead of twice:
  3278.  
  3279.         number *= 4;
  3280.  
  3281. Every time you use the same variable during calculation and for storing the
  3282. result of the equation, you can use the short form instead. The multiplier
  3283. gets moved to the left side of the equal sign.
  3284.  
  3285. The above abbreviation becomes most effective when using long variable
  3286. names. In addition it helps decrease the number of typing errors (the less
  3287. you type, the fewer mistakes you make). For example, look at the following
  3288. abbreviation :
  3289.  
  3290.         the_user_input[index] += '0';
  3291.  
  3292. The above abbreviation corresponds to :
  3293.  
  3294.         the_user_input[index] = the_user_index[index] + '0';
  3295.  
  3296. Another advantage is the speed difference between the long version of the
  3297. code and the abbreviated version of the code. The execution speed of each
  3298. compiled code is different; the abbreviated version executes in less time
  3299. than the original. The compiler knows what values are used and where to
  3300. store the result. This can save a lot of unneccesary calculation time.
  3301.  
  3302.                                 PAGE 95
  3303.  
  3304. ---------------------------------------------------------------------------
  3305.  
  3306. Implementing operator abbreviations is fairly easy to do. All arithmetic
  3307. operators can be changed into abbreviated form as seen in the following
  3308. list:
  3309.  
  3310.         +=
  3311.         -=
  3312.         *=
  3313.         /=
  3314.         %=
  3315.         etc.....
  3316.  
  3317. Consider the following expression. Can you see any possibilities for
  3318. abbreviating the code?
  3319.  
  3320.         value = value * (5 + number);
  3321.  
  3322. The line is already written in such a way that the operator to abbreviate
  3323. becomes immediately obvious. It is the multiplication operator. So, if you
  3324. change the equation into abbreviated form, the source code looks like this:
  3325.  
  3326.         value *= 5 + (number);
  3327.  
  3328. Now for the same thing in reverse. The operator and the named variable can
  3329. be attached to the terms using parenthesis. The following equation also has
  3330. potential for becoming an abbreviated version :
  3331.  
  3332.         var *= number1 - number2;
  3333.  
  3334. Corresponds to :
  3335.  
  3336.         var = (number1 - number2) * var;
  3337.  
  3338.                                 PAGE 96
  3339.  
  3340. ---------------------------------------------------------------------------
  3341.  
  3342. 11.1 INCREMENT AND DECREMENT.
  3343.  
  3344. Shorthand notation can be carried a step beyond arithmetic operators. The
  3345. operators ++ and -- increment and decrement a variables contents by one.
  3346. The ++ operator increments the specified varaible by one, and is therefore
  3347. called the increment operator. The -- operator (called the decrement
  3348. operator) acts in the opposite manner and decrements (decreases) the
  3349. specified variable by one. These operators appear as follows:
  3350.  
  3351.         main()
  3352.         {
  3353.            int i;
  3354.            i = 1;
  3355.            while(i++ < 100)
  3356.                 printf("%d",i);
  3357.         }
  3358.  
  3359. This short program is deceptive. Up to the WHILE loop everything is clear.
  3360. The i variable contains the value 0. Now comes the expression:
  3361.  
  3362.         i++ < 100
  3363.  
  3364. First the computer sees if i is less than 100. Then it increments the value
  3365. of i by one regardless of the results of the test. This corresponds to the
  3366. following if/else/while:
  3367.  
  3368.         if( i<100)
  3369.                 condition = 1;
  3370.         else
  3371.                 condition = 0;
  3372.         i = i + 1;
  3373.         while(condition)
  3374.         ...............
  3375.  
  3376. Here all four listed directives are executed within the parenthesis. That
  3377. makes the increment operator very powerful.
  3378.  
  3379. If gets better. The increment and decrement operators can be placed before
  3380. or after the variable to serve different purposes. The location is
  3381. important as youll see. A simple example will illustrate :
  3382.  
  3383.         i = j++;
  3384.  
  3385.                                 PAGE 97
  3386.  
  3387. ----------------------------------------------------------------------------
  3388.  
  3389. Assuming that J contains the value 3, i also contains 3. Then the value of
  3390. J is incemented by one to 4. In contrast, the next line places the operator
  3391. on the other side of the variable:
  3392.  
  3393.          i = ++j;
  3394.  
  3395. With the same assumptions, the content of J is incremented to 4 and then
  3396. the variable i is assigned that value. Both variables now contain 4.
  3397.  
  3398. Remember, if you preceed a variable with an increment or decrement
  3399. operator, the content of the variable changes before it is used for
  3400. additional tests. If the operator follows the variable, first the current
  3401. value is used and then the variable is incremented or decremented. It is
  3402. important to remember this small but decisive difference. Examine the
  3403. output of the two programs on the screen. The first number which appears
  3404. there is two. That is clear since the starting value of i was one which was
  3405. already incremented inside the loop head with WHILE. For this reason the I
  3406. at the time the printf occurred already had the value 2.
  3407.  
  3408. These operators help to write fast and compact programs. They are even more
  3409. efficient than the abbreviations using the equal signs.
  3410.  
  3411.                                 PAGE 98
  3412.  
  3413. ---------------------------------------------------------------------------
  3414.  
  3415. 11.2 INITIALISATION , DEFINITION AND DECLARATION
  3416.  
  3417. INITIALISATION :-
  3418.  
  3419.  
  3420. These 3 concepts are very important for the C programmer and should not be
  3421. confused. Lets begin with INITIALISATION. It describes the first
  3422. assignment of a value to a variable. After this point you know what the
  3423. variable contains. Before the variable can be initialised it must be
  3424. defined or declared. Definition takes forms similar to the following :-
  3425.  
  3426.         int index;
  3427.         char string[80];
  3428.  
  3429. When the compiler reaches this point, it knows the variables and sets aside
  3430. the necessary memory area for them. An integer value generally requires two
  3431. bytes. The variable STRING requires 80 bytes since every char element
  3432. requires 1 byte. Functions can also be defined. Up to now only the
  3433. definition of MAIN was mentioned. If you declare a function or variable,
  3434. this only tells the program that such a variable or function was defined
  3435. somewhere. For this reason no memory is allocated.
  3436.  
  3437. DEFINITION :
  3438.  
  3439. Heres a tip for saving line of code. Variables can be initialised during
  3440. definition. That saves one program line :
  3441.  
  3442.         int index = 0;
  3443.  
  3444. Any expression can be assigned to the newly defined variable. The string
  3445. length which was determined with the STRLEN function can be used during
  3446. initialisation as follows :
  3447.  
  3448.         int end = strlen(string) - 1;
  3449.  
  3450. Of course, string must have previously been defined :
  3451.  
  3452. Some coding can seem exaggerated, but there is no limit to your
  3453. imagination.
  3454.  
  3455.         long middle = 4*((strlen(string)+1)/2+1)-strlen(string2)/3;
  3456.  
  3457. DECLARATION :
  3458.  
  3459. If you write a large program stored in several modules(files) a variable
  3460. used by all modules only requires a single memory allocation. The
  3461. definition is in one file and all the other files only contain the
  3462. corresponding declaration. Declaration is made with the C word EXTERN. The
  3463. compiler knows that the memory was reserved externally through another
  3464. file. Otherwise the linker stops linking. Example :
  3465.  
  3466.                                 PAGE 99
  3467.  
  3468. ---------------------------------------------------------------------------
  3469.  
  3470.         extern char pass_word[80];
  3471.         extern int error_nr;
  3472.  
  3473. The example above shows that the data type must also be specified. This
  3474. provides all the information necessary to the compiler about the variable.
  3475. The function declaration is similar.
  3476.  
  3477.         extern long atoi();
  3478.  
  3479. If you define the function in the same file, the EXTERN can be omitted. The
  3480. declaration is still required since the compiler knows the function names
  3481. and their data types only at the end of the file.
  3482.  
  3483.  
  3484.                                 PAGE 100
  3485.  
  3486. ---------------------------------------------------------------------------
  3487.  
  3488. 11.3 MULTIPLE ASSIGNMENTS AND DIRECTIVE VALUE IN C.
  3489.  
  3490. Source code can also be abbreviated by using multiple assignments. If
  3491. several variables are to be assigned the same value, individual assignments
  3492. were previously required for every variable. The same value was given for
  3493. each :
  3494.  
  3495.         begin = 0;
  3496.         sum = 0;
  3497.  
  3498. However, the following linme performs the same function :
  3499.  
  3500.         begin = sum = 0;
  3501.  
  3502. The assignment is from right to left. First 0 is assigned to sum and then
  3503. begin gets the contents of sum which is zero. A term with more simultaneous
  3504. assignments could be enclosed in parenthesis which would make the sequence
  3505. more readable. Here's one version :
  3506.  
  3507.         a = b = c = d = 2;
  3508.  
  3509. This version shows added parenthesis for readability :
  3510.  
  3511.         a = (b = (c = (d = 2));
  3512.  
  3513. Individually expressed, the two above lines correspond to the expression :
  3514.  
  3515.         d = 2;
  3516.         c = 2;
  3517.         b = 2;
  3518.         a = 2;
  3519.  
  3520. Multiple assignment is possible since every expression has a value (the
  3521. result of the last operation performed). For example, the value of (d=2) 2,
  3522. of (index = strlen(string)) strlen (string). Except for large
  3523. initialisations of variables, the value of an expression can be used almost
  3524. everywhere. It also shows who knows C well. The shorter formulation will
  3525. identify the professional.
  3526.  
  3527. Examples can show this better. Here are some more values for expressions :
  3528.  
  3529.         (2)             2
  3530.         (a)             a
  3531.         (a *= 3)        a*3
  3532.         (a=(b=(a+2)-3)) a-1
  3533.  
  3534.                                 PAGE 101
  3535.  
  3536. ---------------------------------------------------------------------------
  3537.  
  3538. The last example must be dissected into its components to reach the same
  3539. results :
  3540.  
  3541.         (a=(b=(a+2)-3))
  3542.         (a=(b=a-1))
  3543.         (a=(a-1))
  3544.         (a-1)
  3545.  
  3546. Of course, the advantages of the multiple assignment can be used during the
  3547. definition and initialisation. The following line os permissible:
  3548.  
  3549.         int start = value = 0;
  3550.  
  3551. The variable VALUE must be predefined and initialised (very important)
  3552. which is the case here.
  3553.  
  3554.                                 PAGE 102
  3555.  
  3556. ---------------------------------------------------------------------------
  3557.  
  3558.                         CHAPTER 12 - FUNCTIONS.
  3559.  
  3560. You read in the introduction that a C program sometimes consists of many
  3561. different functions. Up to now only one has been defined (the MAIN
  3562. function). Its time to start writing programs which contain several
  3563. functions developed by you.
  3564.  
  3565. FUNCTION STRUCTURE 
  3566.  
  3567. First the formal structure of a function definition. You must specify the
  3568. function name, preceeded by the data type returned by the function. The
  3569. name must correspond to the usual rules for variable name.
  3570.  
  3571. Parenthesis containing the arguments follow the name. If no such values
  3572. exist (e.g. the MAIN function) none can be indicated. If such arguments are
  3573. expected, these variables must be declared. The values are important since
  3574. most functions get information from other functions which are then
  3575. processed. Then follow the executable commands, also enclosed in
  3576. parenthesis.
  3577.  
  3578. Let's look again at a simple version of the MAIN function :
  3579.  
  3580.         main()
  3581.         {
  3582.          ..
  3583.          ..
  3584.         }
  3585.  
  3586. The first item to be encountered according to the specification is the data
  3587. type which the function returns. Since the MAIN function doesnt return any
  3588. values to the calling program, the data type is omitted. The word VOID
  3589. usually appears preceeding a function that returns nothing.
  3590.  
  3591. Next the function name (main) is specified, followed by a pair of
  3592. parenthesis. Since no values are passed to the main program, no data
  3593. appears between the parenthesis. The variable declaration is also omitted,
  3594. since nothing is passed. Then follow the other executable instructions
  3595. within the braces, which up to now was the complete executable program.
  3596.  
  3597.                                 PAGE 105
  3598.  
  3599. --------------------------------------------------------------------------
  3600.  
  3601. 12.1 FUNCTIONS WITH ARGUMENTS.
  3602.  
  3603. The next step is to dissect the program into individual tasks. You can
  3604. write a short function for every partial task. For example, a function to
  3605. compute the square of a value requires no great mathematical training :
  3606.  
  3607.         double square(x)
  3608.         
  3609.         float x;
  3610.         {
  3611.            double q_number;
  3612.            printf("The square of %f\n is ", x);
  3613.            q_number = x * x;
  3614.            return q_number;
  3615.         }
  3616.  
  3617. THE SQUARE FUNCTION :
  3618.  
  3619. The above routine defines a function named SQUARE which in turn returns a
  3620. double value to the calling program. As a parameter to be passed, a FLOAT
  3621. value called x is required. At the end of the routine a new C keyword
  3622. appears, the RETURN keyword. It delivers the required result of the
  3623. specified data type to the caller and also ends the function.
  3624.  
  3625. It is important that no semi-colon follows the function name. There must be
  3626. a semi-colon after each parameter declaration. This differentiates a
  3627. function definition (without semicolon) from a function call (with
  3628. semicolon). The following line identifies that a function named square is
  3629. to be used by the main program :
  3630.  
  3631.         double square();
  3632.  
  3633.         main()
  3634.         {
  3635.                 float value = 3.0;
  3636.                 double result;
  3637.                 ............
  3638.                 ............
  3639.                 result = square(value)
  3640.         }
  3641.  
  3642. The names of the parameters passed by the calling function need not be
  3643. identical to those of the called function. However, the data types must be
  3644. the same. Notice that the line in which the square function is declared as
  3645. a function which returns a DOUBLE value.
  3646.  
  3647.                                 PAGE 106
  3648.  
  3649. ---------------------------------------------------------------------------
  3650.  
  3651.  
  3652. The declaration can be omitted if integer values are returned. The same is
  3653. true for the definition of a function. If the function returns integer
  3654. values, a data type need not preceed the function name. This is only
  3655. possible with the data type INT. All other types must be declared and
  3656. supplied with the proper data type during the definition. If one of these
  3657. data types is contradictory (perhaps because the declaration forgot a
  3658. DOUBLE function) the resulting values will be wrong. While the C language
  3659. permits much freedom to the programmer, this can cause much trouble.
  3660.  
  3661.                                 PAGE 107
  3662.                                 
  3663. ---------------------------------------------------------------------------
  3664.  
  3665. 12.2 FUNCTIONS WITHOUT RETURN VALUES.
  3666.  
  3667. Some functions return no values. These functions can be declared as VOID,
  3668. if the compiler has implemented this keyword. This can improve the speed
  3669. somewhat since the parameters need not be prepared for the calling
  3670. function. Even that may be omitted, which is the reason why some C
  3671. compilers dont define the VOID type.
  3672.  
  3673.         /* key.c 12.2 */
  3674.         void key(string)  /* without return value -- void */
  3675.         char string[80];
  3676.  
  3677.         {
  3678.           int i;
  3679.           for (i=0; string[i] > 0;i++)
  3680.             printf("%c", string[i]+1); /* from 'a' makes 'b'*/
  3681.         }
  3682.  
  3683.         void main()
  3684.         {
  3685.            char text[81];
  3686.            void key();
  3687.  
  3688.            printf("please input some text\n");
  3689.            scanf("%80s",text);
  3690.            key(text);
  3691.            printf("in the original it was %s\n",text);
  3692.         }
  3693.  
  3694. The new defined functions are called exactly like the routines from the
  3695. libraries. In this example the MAIN function stands at the end of the file.
  3696. The routine names KEY is declared as a function which returns nothing or
  3697. VOID. That is important since the definitions would contradict themselves
  3698. during usage in MAIN. If the function had not been declared the compiler
  3699. would assume that it should return INT objects. It returns nothing.
  3700.  
  3701.                                 PAGE 108
  3702.  
  3703. ---------------------------------------------------------------------------
  3704.  
  3705. 12.3 OTHER FUNCTIONS.
  3706.  
  3707. Another function which does not require a result is STRCPY. This routine
  3708. copies strings, and performs general string handling. Even though its
  3709. included in every C compilers library file, it is interesting to see how it
  3710. can be programmed.
  3711.  
  3712. 12.3.1 STRCPY - VERSION 1
  3713.  
  3714. This copies one string to another. Unlike the previous example, you dont
  3715. know how many entries are in each string. This can be omitted. It is enough
  3716. for the compiler to know that it will get a string.
  3717.  
  3718. In the routine itself, a counter tests all entries. They are copied until
  3719. the routine reaches the EOS character (the end character which must also be
  3720. transmitted).
  3721.  
  3722.         #define EOS '\0'
  3723.  
  3724.         strcpy(to,from)
  3725.         char to[], from[];
  3726.         {
  3727.            int i = 0;
  3728.            while((to[i] = from[i]) != EOS)
  3729.                 i++;
  3730.         }
  3731.  
  3732. The function is indifferent to the memory requirements of the array, since
  3733. it doesnt have to set aside any memory. The STRCPY works directly with the
  3734. strings passed to it from the calling function. The strings may be of
  3735. different lengths.
  3736.  
  3737. What do you think of the terminiation conditions in the WHILE loop?. The
  3738. position of the parenthesis makes the processing clear. First it is the
  3739. assignments of from[i] to to[i]. The expression in the parenthesis also has
  3740. the value from[i], and also the character which was copied. This is now
  3741. compared with the end code character. If you copy the EOS, the condition is
  3742. no longer true and the loop terminates. Otherwise it increments the current
  3743. counter and remains in the loop.
  3744.  
  3745.                                 PAGE 109
  3746.  
  3747. --------------------------------------------------------------------------
  3748.  
  3749. The actual loop body has only a peripheral role. The main action occurs in
  3750. the ending conditions. Experiment with this function. Notice that the
  3751. string into which the copy is stored appears first. Here is a complete
  3752. example program :
  3753.  
  3754.         /* copysrt.c    12.3.1  */
  3755.         #define EOS '\0'
  3756.         #define MAXLEN 81
  3757.  
  3758.         strcpy(to,from)
  3759.         char to[], from[];
  3760.         {
  3761.            int i = 0;
  3762.            while((to[i] = from[i]) != EOS)
  3763.              i++;
  3764.         }
  3765.  
  3766.         void main()
  3767.         {
  3768.            char s1[MAXLEN], s2[MAXLEN], s3[MAXLEN];
  3769.  
  3770.            printf("Your name please\n");
  3771.            scanf("%40s",s1);
  3772.            strcpy(s3,s1);
  3773.            strcpy(s2, "TEXT in s2");
  3774.            printf("Therefore %s, in s2 is \"%s\".", s1,s2);
  3775.            printf("I hope %s, that everything is clear!\n",s3);
  3776.         }
  3777.  
  3778. The STRCPY function can be used to initialise strings since the following
  3779. expression is not permitted in C :
  3780.  
  3781.         WRONG:
  3782.  
  3783.         main()
  3784.         {
  3785.            char text[20] = "This_is_text!";
  3786.              . . . . . .
  3787.         }
  3788.  
  3789.         RIGHT:
  3790.  
  3791.         main()
  3792.         {
  3793.            char text[20];
  3794.            strcpy(text,"This_is_text!");
  3795.               . . . . .
  3796.         }
  3797.  
  3798. This copies the complete string into the variable text.
  3799.  
  3800.                                 PAGE 110
  3801.  
  3802. --------------------------------------------------------------------------
  3803.  
  3804. 12.3.2 STRLEN.
  3805.  
  3806. You used the STRLEN function earlier in this book. It is simple to write
  3807. and return a value. The passed length of the string is a whole number and
  3808. should be an integer value.
  3809.  
  3810.         strlen(string)
  3811.         char string[];
  3812.         {
  3813.            int i = 0;
  3814.            while(string[i])
  3815.             i++;
  3816.            return(i);
  3817.         }
  3818.  
  3819. A nice short function! The expression string[i] is always the content of
  3820. this element. This means that the expression is only 0 (false) when the end
  3821. character \0 (EOS) has been reached. The counter which corresponds to the
  3822. length of the string passes to the calling function as an integer value
  3823. through a return directive. This function doesnt have to be declared in the
  3824. calling function because it returns an INT value.
  3825.  
  3826. If the return directive passes data, it must be assured that the value has
  3827. the proper data type. If the function definition states that the routine
  3828. returns a CHAR element, there should be a variable or constant of the CHAR
  3829. type. Some compilers will not tolerate such mistakes and will issue an
  3830. errror message. Others are indifferent and convert the result into the data
  3831. type indicated in the definition. Its better to do it right in the first
  3832. place.
  3833.                 
  3834.                                 PAGE 111
  3835.  
  3836. -------------------------------------------------------------------------
  3837.  
  3838.                         CHAPTER 13 - ARRAYS.
  3839.  
  3840.  
  3841. Up to now strings have been used as if they were a special data
  3842. type. A string is actually multiple char entries. A string of similar
  3843. objects is called an array. Arrays can also be made using INT or FLOAT data
  3844. types as well as CHAR types. Any elementary data type can be stored in an
  3845. array. Several similar variables can be accessed through a single
  3846. identifier. A single element is accessed by using a subscript called the
  3847. index (counter). The definitionn of a long array differs little from string
  3848. definition:
  3849.  
  3850.         long value[20];
  3851.  
  3852. This line reserves 20 elements of type long for the variable value. To
  3853. indicate the end of a string, the last entry contains the value 0, i.e. 
  3854. assigns the escape sequence \0. For this reason the definition of a string
  3855. (character array) requires one element more than needed for the actual
  3856. string. No such requirements exist for other array types: Only as many
  3857. entries are defined as required by the data.  A value assignment of one
  3858. element is possible only by providing the index. For example :
  3859.  
  3860.  
  3861.         value[0] = 'O';
  3862.         value[1] = 707;
  3863.         value[2] = 31415;
  3864.  
  3865. The index value of the first element always starts with 0. Using this
  3866. method you can create a string using one character at a time;
  3867.  
  3868.         char string[80];
  3869.  
  3870.         string[0] = 'o';
  3871.         string[1] = 'k';
  3872.         string[2] = '\0';
  3873.  
  3874. This tedium can be avoided by using the STRCPY function. The assignment
  3875. sequence above would store the string value 'ok' into the variable STRING,
  3876. and is terminated with the usual end code \0.
  3877.  
  3878. Again the difference between a single character and a string of characters
  3879. should be emphasized. The difference between "K" and 'K' is that "K" is a
  3880. string, while 'K' is a character. If a letter is enclosed in "Quotation
  3881. marks" like a character string it is a string. It is also terminated with a
  3882. \0 so that "K" consists of two characters, the K and \0. However,'K' is
  3883. only a single character. This condition must always be observed since all
  3884. operating system routines assume that the string terminates with \0. The
  3885. last element that may be accessed has a value of 79, according to the
  3886. declaration above of STRING[80] (counting starts with 0)
  3887.  
  3888.                         PAGE 115
  3889.  
  3890. --------------------------------------------------------------------------
  3891.  
  3892.  
  3893. 13.1 MULTI-DIMENSIONAL ARRAYS.
  3894.  
  3895. Up to now we've been using one-dimensional arrays, i.e., variables which
  3896. use a single subscript. Multi-dimensional arrays have elements like a
  3897. one-dimensional array. However, multi-dimensional arrays have multiple
  3898. elements. For example, if you were designing a chess game in C you might
  3899. use an 8 * 8 array for the chess board data:
  3900.  
  3901.         int field[8][8];
  3902.  
  3903. Both elements are of course between 0 and 7. You need two subscripts to
  3904. access a single field:
  3905.  
  3906.         printf("Contents of line 2 column 4 %d\n",field[1][3]);
  3907.  
  3908. You can define an array with upto 5 sets of elements:
  3909.  
  3910.         long content[4][5][6][7][8];
  3911.  
  3912. Please observe that arrays can quickly occupy large amounts of memory. The
  3913. array would require 4*5*6*7*8 * 4 (size of a single long element)
  3914. bytes(26880 bytes or 26.25k).
  3915.  
  3916. Data can only be stored sequentially in memory. The user must get away from
  3917. the notion that a two-dimensional array is located in two tables which are
  3918. one in front of the other. How would a five-dimensional array be stored?
  3919. Since all elements are stored in a long series (One-dimensional) there is a
  3920. rule which must be followed. The first index changes only when all elements
  3921. which belong to it's group are stored. During the second index that occurs
  3922. more frequently and the last index changes changes with every element. This
  3923. concept is easier to understand in a listing which shows the position of
  3924. the entries in menory. Assuming a definition of INT POS[4][3];, entries in
  3925. memory are ;
  3926.  
  3927.         [0][0]
  3928.         [0][1]
  3929.         [0][2]
  3930.         [1][0]
  3931.         [1][1]
  3932.         [1][2]
  3933.         [2][0]
  3934.          ....
  3935.          ....
  3936.         [3][1]
  3937.         [3][2]
  3938.  
  3939.                                 PAGE 116
  3940.  
  3941. --------------------------------------------------------------------------
  3942.  
  3943. To conclude this chapter we want to present a program which operates with
  3944. arrays, and touches on many topics previously discussed. The program tests a
  3945. series of numbers, passes them to a routine which adds them and receives a
  3946. sum back. Then it makes statistical evaluations to determine if it's worth
  3947. storing the values. An array stores the data entered. There are also some
  3948. tricks which should be examined closely;
  3949.  
  3950.         /* array.c 13 */
  3951.         #define FALSE 0
  3952.         #define TRUE 1
  3953.         #define MAXENTRY 20
  3954.  
  3955.         long total(); /* declaration of the function.*/
  3956.  
  3957.         void main()
  3958.         {
  3959.                 int i, number, end = FALSE;
  3960.                 long sum, data[MAXENTRY];
  3961.  
  3962.                 for(i=0; i<MAXENTRY && !end; i++)
  3963.                 {
  3964.                         printf("Enter %d. value ",i+1);
  3965.                         scanf("%6ld", &data[i]); /* 6 digit limit */
  3966.                         if(!data[1])
  3967.                                 end = TRUE;
  3968.                  }
  3969.         }
  3970.  
  3971.         number = i - end; /* if last data 0, then one less */
  3972.         sum = total(data,number);
  3973.         printf("The sum of all %d values is %ld\n", number , sum);
  3974.                 printf("Deviation from Average %.9lf:\n", (double) sum / 
  3975.                  number );
  3976.         for(i=0;date[i] > 0 ; i++)
  3977.                 printf("value %d: %5.9lf%%\n", i+1 , data[i] * 100.0 / 
  3978.                 ( (double) sum / number ) - 100.0 );
  3979.         }
  3980.  
  3981.         long total(array,cnt)
  3982.         long array[];
  3983.         int cnt;
  3984.         {
  3985.                 long sum = 0
  3986.  
  3987.                 while(cnt--) /* short and precise */
  3988.                         sum += array[cnt];
  3989.                 return sum;
  3990.         }
  3991.  
  3992. LATTICE
  3993.  
  3994. The library for mathematical functions and floating point numbers must be
  3995. linked with the standard library. Example:
  3996.  
  3997.         LC -Lm array
  3998.  
  3999.                                 PAGE 117
  4000.  
  4001. --------------------------------------------------------------------------
  4002.  
  4003. AZTEC
  4004.  
  4005. If you work with the Aztec compiler, the library for mathematical functions
  4006. and floating point numbers must be linked with the standard  c.lib. 
  4007. Example:
  4008.  
  4009.         cc +L array.c
  4010.         ln array.0 -lm -lc
  4011.  
  4012. First some information on the program. To make it more secure, only 20
  4013. entries are permitted. The #define MAXENTRY allows you to adapt the program
  4014. to larger input.
  4015.  
  4016. The declaration of the ADD function is important. since this function uses
  4017. LONG values, the compiler must be told this. The declaration can be
  4018. performed within the MAIN function.
  4019.  
  4020. The && operator ends the for loop which connects two tests logically with
  4021. an AND. If not all entries are occupied and the varaible end is unequal to
  4022. 0, the loop executes.
  4023.  
  4024. NEGATION
  4025.  
  4026. The negation operator converts END into the logical opposite. At the
  4027. beginning the varaible contains the value 0 so that the expression becomes
  4028. !end 1. The reverse occurs when end is set to 1 and the negation !END is
  4029. used to leave the loop. This happens when the user enters the number 0
  4030. indicating the end of the input.
  4031.  
  4032. The first entry in the array requires the index 0. Since the count usually
  4033. starts at one, a 1 is added to the current index during text output. In the
  4034. formulation of the SCANF  function, the following is most important:
  4035.  
  4036.         &entry[i]
  4037.  
  4038. If another array was input no & character appears. That was the big
  4039. exception. Since entry[i] and not ENTRY was written, this is not an array
  4040. but a perfectly normal LONG varaible. During the SCANF routine it is
  4041. equipped with the & like all elementary data types. The fact that this
  4042. variable is in a long string of elements doesn't concern the SCANF
  4043. function.
  4044.  
  4045. The following If test also merits closer examination. This is a typical
  4046. case of C abbreviation. The test should pass the value 1 to the end
  4047. varaiable if the current input was 0. The following shows this;
  4048.  
  4049.         if(entry[i]==0)
  4050.           ...........
  4051.  
  4052. If entry[i] contains a zero this expression is also zero. With the help of
  4053. the negation operator a true result is obtained. Especially for the test
  4054. ==0 or !=0, the abbreviations are often placed in the location wherre you
  4055. would expect to find an explicit value. It doesn't complicate the matter
  4056. but the uer must know what is hidden there.
  4057.  
  4058.                                 PAGE 118
  4059.  
  4060. --------------------------------------------------------------------------
  4061.  
  4062. When the loop finishes, either because 20 entries have been made, or the
  4063. last entry was 0, the total number of the stored data is calculated. The
  4064. ADD function gets the necessary data (the array with the input and the
  4065. number of values to be added). This routine returns the sum. With this
  4066. information the deviation of each entry from the average can be calculated.
  4067. If the task of the program was only to add a series of numbers, no arrays
  4068. would be needed but all entries could be summed after their entry.
  4069.  
  4070.                                 PAGE 119
  4071.  
  4072. ==========================================================================
  4073.  
  4074.                    CHAPTER 14.
  4075.  
  4076.  
  4077. 14. MORE ABOUT LOOPS.
  4078.  
  4079. This chapter takes you through some of the finer points of using loops in
  4080. the C programming language. You've already seen FOR loops and WHILE loops.
  4081.  
  4082. It also demonstrates some refinements to the FOR loop; statements which
  4083. help control loop programming (BREAK and CONTINUE); and a function for
  4084. switching around within a loop (SWITCH).
  4085.  
  4086. ---------------------------------------------------------------------------
  4087.  
  4088. 14,1  MORE ABOUT THE FOR LOOP
  4089.  
  4090. We described the FOR loop earlier in this book. Now we'll look at the
  4091. limitations and flexibility of the FOR loop. 
  4092.  
  4093. Individual components of the FOR loop are separated by semi-colons. Several
  4094. statements can be placed within the initialisation and the increment
  4095. expressions. They use commas as separators, instead of Semi-Colons. This is
  4096. how the FOR loop can be used :
  4097.  
  4098.         for(sum = 0, i = 1; i<=20; i++)
  4099.         sum += 1;
  4100.  
  4101. or
  4102.  
  4103.         for(i=1, j=0; i<10; i +=2, j+=3)
  4104.  
  4105. This is the usual construction of a FOR loop. Since C permits other
  4106. variations this example is presented;
  4107.  
  4108.         for(printf("now we start"); ; printf("Bang\n"), i++)
  4109.                 if ((c = input()) == 'e' )
  4110.                         break;
  4111.  
  4112. The text 'now we start!' appears at the beginning of the loop. A test is
  4113. then made to determine if the condition located between the semicolons is
  4114. true. This is always true since there is nothing there.
  4115.  
  4116. You may recall that, under every condition, a null value is always
  4117. considered a false condition. Everything else is considered logically true.
  4118. The condition in the loop is always true. The only way to stop the program
  4119. is to press the <e> key, provided there is an input function.
  4120.  
  4121.                                 PAGE 123
  4122.  
  4123. --------------------------------------------------------------------------
  4124.  
  4125. 14.2 BREAK
  4126.  
  4127. If the test for IF is true the BREAK statement is carried out. The break
  4128. statement ends the currently executing loop immediately and forces the
  4129. program to continue with the statement that follows the loop that just
  4130. ended. The BREAK statement is the only way to break free of a loop at any
  4131. time.
  4132.  
  4133. Look at the program in the precedding section. The increment proceeds in an
  4134. unusual fashion. a PRINTF call can be found there. This printf executes at
  4135. the end of each loop execution (notice that not much remains of the
  4136. original construction.). An endless loop, which doesn't have an
  4137. initialisation, a test or incrementation would appear as follows;
  4138.  
  4139.         for(;;)
  4140.           {
  4141.           ......
  4142.           }
  4143.  
  4144. A FOR loop can always be replaced with a WHILE loop, and vice versa.
  4145. The general format is;
  4146.  
  4147.         for(term1; term2; term3)
  4148.             {
  4149.                other directives
  4150.             }
  4151.  
  4152. OR
  4153.  
  4154.         term1;
  4155.         while(term2)
  4156.            {
  4157.               other directives
  4158.               term3;
  4159.             }
  4160.  
  4161.                                 PAGE 124
  4162.  
  4163. ---------------------------------------------------------------------------
  4164.  
  4165. 14.3 CONTINUE
  4166.  
  4167. The CONTINUE statement does the opposite of the BREAK statement. Instead of
  4168. leaving the loop immediately, the program jumps to the next directive in
  4169. line for execution after the last line within the loop is processed. For
  4170. the three types of loop this is;
  4171.  
  4172.         1.  The body of the WHILE loop (within the parentheses)
  4173.         2.  The incrementation of the FOR loop, therefore FOR(...; ...;
  4174.             continue)
  4175.         3.  The directive after DO in DO....WHILE.
  4176.  
  4177. EXAMPLE:
  4178.  
  4179.         calculate(field)
  4180.         double field[];
  4181.         {
  4182.            int i;
  4183.  
  4184.            for(i=0; i<number; i=i+1)
  4185.              {
  4186.                 if(field[i] == 0.0)
  4187.                   continue;
  4188.  
  4189.                   continue here....!
  4190.               }
  4191.          }
  4192.  
  4193. If an entry within field should have a zero value, the CONTINUE directive
  4194. then executes. The program continues at location i=i+1 as if the loop block
  4195. had been terminated.
  4196.  
  4197.                                 PAGE 125
  4198.  
  4199. --------------------------------------------------------------------------
  4200.  
  4201. 14.4 THE SWITCH DIRECTIVE.
  4202.  
  4203. This directive allows you to handle several similar comparisons. This is
  4204. presented in the following short program:
  4205.  
  4206.         /* switch.c 15.4 */
  4207.         void main()
  4208.         {
  4209.           int number;
  4210.  
  4211.           printf("Please input a number!\n");
  4212.           while(1)
  4213.             {
  4214.                scanf("%d",&number);
  4215.                switch(number)
  4216.                  {
  4217.                    case 9:
  4218.                       printf("Larger than 8 ");
  4219.                    case 8:
  4220.                       printf("Larger than 7 ");
  4221.                    case 7:
  4222.                       printf("larger than 6 ");
  4223.                    case 6:
  4224.                       printf("Larger than 5 ");
  4225.                    case 5:
  4226.                       printf("Larger than 4 ");
  4227.                    case 4:
  4228.                       printf("Larger than 3 ");
  4229.                    case 3:
  4230.                       printf("Larger than 2 ");
  4231.                    case 2:
  4232.                       printf("Larger than 1 ");
  4233.                    case 1:
  4234.                       printf("Larger than 0 ");
  4235.                    case 0:
  4236.                       printf("Number!\n");
  4237.                       break;
  4238.                    default:
  4239.                       printf("Single number only!\n");
  4240.                  }
  4241.                if(number == 4711)
  4242.                  break; /* Leave endless loop */
  4243.             }
  4244.         }
  4245.  
  4246.  
  4247. The switch statement if given the value to be tested (SWITCH(c)). Within
  4248. the block of statements, this value is compared with the values behind the
  4249. keyword CASE. This value, which must be followed by a colon, is then
  4250. followed by the statements to be executed. If the 
  4251.  
  4252.                                 PAGE 126
  4253.                                 
  4254.  
  4255. comparison is positive,
  4256. if all values agree, the statements following CASE are executed. If the
  4257. comparisons are negative, the next comparison is tested and all statements
  4258. to the next CASE are skipped.
  4259.  
  4260. The C keyword DEFAULT permits execution of statements if no comparisons
  4261. were successful. In comparison with the IF test, DEFAULT corresponds to the
  4262. ELSE branch of the IF construction. If a test is positive, all of the
  4263. following commands are executed. A STOP doesn't occur before the NEXT case.
  4264. In order to stop this process a BREAK statement is required for each CASE
  4265. statement.
  4266.  
  4267. If the character passed for the test is for example a 5, all directives
  4268. (also those behind case 4,3 etc..) are executed up to the next BREAK
  4269. directive, This causes direct termination of a loop or in this case the
  4270. SWITCH directive.
  4271.  
  4272. Even if several directives are behind a CASE, parenthesis are not required.
  4273. With SWITCH all elementary data types except for floating point numberrs
  4274. can be compared.
  4275.  
  4276.                                 PAGE 127
  4277.  
  4278. ==========================================================================
  4279.  
  4280.                   CHAPTER 15. POINTERS AND ADDRESSES.
  4281.  
  4282.  
  4283. This chapter discusses the most important components of the C language.
  4284. Pointers are loved by some and hated by others. In a discussion of the
  4285. advantages and disadvantages of C, inevitably the word pointer will be
  4286. mentioned. It is possible to write fast and short routines with pointers,
  4287. but some programmers who have never worked with pointers are completely
  4288. confused by them.
  4289.  
  4290. ----------------------------------------------------------------------------
  4291.  
  4292. 15.1 ADDRESSES.
  4293.  
  4294. Lets start slowly. The pointer concept has close connections to the address
  4295. concept. During the call of the SCANF function, the & (address) operator
  4296. had to be placed in front of most variables. This construction allows the
  4297. determination of a variable's memory address. All data , wether floating
  4298. point numbers, integers or characters are stored somewhere in the computer.
  4299. The position where variable data can be stored is determined by a number
  4300. (the address). In general an address can be compared with the house number
  4301. on a long street. This number is obtained from the variable which is
  4302. preceded by the & character.
  4303.  
  4304. Assume that the variable A was defined and is stored starting at address
  4305. 100. The expression &A would return the value 100. Why are addresses
  4306. required if you can work without them ?.
  4307.  
  4308. The user who experiments with his own functions, may soon find that the
  4309. called function should pass more than one returned value to the calling
  4310. function. It is also difficult to change the value of a variable defined in
  4311. another function. Consider the following section from a program ;
  4312.  
  4313.         {
  4314.             int number = 6;
  4315.             change(number);
  4316.              ...........
  4317.         }
  4318.  
  4319.         change(newnum)
  4320.         int newnum;
  4321.         {
  4322.             newnum = 5;
  4323.         }
  4324.  
  4325.                                 PAGE 131
  4326.  
  4327.  
  4328.  
  4329. The CHANGE function receives a copy of the content of number only during
  4330. the call. If this function changes the value of the variable NEWNUM, the
  4331. original which is in the calling function remains unchanged. This was
  4332. already used in a program . Examine the program which calculates the sum of
  4333. individual array entries. The value AMT decrements to zero, while the
  4334. variable NUMBER is used later for calculation of the average.
  4335.  
  4336. Now we have a way to pass the address of the variable. The calling function
  4337. can access them directly and the function does not contain a copy of the
  4338. variables. In what data type should this address be stored ?
  4339.  
  4340.                                 PAGE 132
  4341.  
  4342. --------------------------------------------------------------------------
  4343.  
  4344. 15.2 POINTERS
  4345.  
  4346. Principally the address could be stored in an INT or LONG variable. This
  4347. depends on the size of the INT type and the processor, as well as how many
  4348. bits are required for an address. The Amiga requires 32 bits, a long value.
  4349. Not all compilers offer the capability. C may be flexible but some
  4350. compilers are better than others. Storing addresses in LONG variables is not
  4351. good programming because the programs may not be portable to other
  4352. computers. It is better and safer to use the data type adapted for it, the
  4353. POINTER. A pointer is marked by the special character '*'. Since the data
  4354. type is indicated during the definition of a pointer, the pointer is more
  4355. than just a replacement for the LONG variable. What function does the
  4356. pointer serve? As mentioned, it should accept an address. With the address
  4357. it can access an object, here the content of a variable. During the
  4358. definition the pointer obtains additional information about what data type
  4359. is involved. It knows what values it points to. For example;
  4360.  
  4361.         char text[80];
  4362.         char *pointerl /* define pointer to char elements */
  4363.  
  4364.         text[6] = 'a';
  4365.         pointer = &text[6];
  4366.  
  4367. The first command defines a char array (string). The next line is the
  4368. definition of a pointer which is called POINTER. An asterisk preceeds the
  4369. pointer name, which labels it as a pointer. In addition (as in all other
  4370. variable definitions) the data type is indicated. In the next line, the
  4371. character 'a' passes to the array element with the index 6 (7th entry).
  4372. Now the pointer appears which gets the address of element 6 with the
  4373. address operator &. Since POINTER now contains the address of this element,
  4374. it points the character 'a'. The pointer points to another variable,
  4375. text[6]. This is also called REFERENCING, and the reversal of this process
  4376. is called DE-REFERENCING.
  4377.  
  4378. Now access can occur to the letter through the initialised pointer. The
  4379. next directive could be;
  4380.  
  4381.         if(*pointer == 'a')
  4382.             printf("That's it!\n");
  4383.  
  4384. If the element in the memory location should be accessed, the pointer
  4385. variable must be preceeded by the asterisk. The expression *pointer is a
  4386. synonym for test[6] (of course only if *pointer points to that position).
  4387. Also the change of the content of this memory location is possible through
  4388. the pointer;
  4389.  
  4390.         *pointer = 'b';
  4391.  
  4392.                                 PAGE 133
  4393.                                 
  4394.                                 
  4395. After this directive 'b' passes to the location to which the pointer is
  4396. pointing instead of 'a'. Without using the array it's content was changed.
  4397.  
  4398. --------------------------------------------------------------------------
  4399.  
  4400. 15.2.1  THE EXCHANGE FUNCTION WITH POINTER.
  4401.  
  4402. Now a routine which should change the value of the calling function. The
  4403. EXCHANGE function;
  4404.  
  4405.         exchange(xp,yp)
  4406.         int *xp, *yp;
  4407.         {
  4408.             int help = *xp;
  4409.             *xp = *yp;
  4410.             *yp = help
  4411.         }
  4412.  
  4413. This function expects two pointers to the INT values passed as parameters.
  4414. For the exchange the first value which points to xp is saved in the integer
  4415. variable HELP. Then the values are exchanged. The call of the function must
  4416. also be changed in comparison in comparison with the previous calls since
  4417. pointers to their addresses, not INT values are expected.
  4418.  
  4419.         int value1,value2;
  4420.         value1=3;
  4421.         value2=5;
  4422.  
  4423.         exchange(&value1,&value2);
  4424.  
  4425. Perhaps now you understand why, in a SCANF the address operator always had
  4426. to be used. With this function , data are written into the variable, which
  4427. is only possible with pointers and addresses.
  4428.  
  4429. In arrays, especially in the frequently occuring strings, access to
  4430. individual elements can only occur with the index. The address for a single
  4431. entry must be obtained with &array[index]. For the first element in the
  4432. list the following must be constructed;
  4433.  
  4434.         &array[0]
  4435.  
  4436. In C the name of an array is nothing more than the memory address of the
  4437. first element so it can be abbreviated. For &array[0] can be written ARRAY.
  4438. Both return the address of the first element, not it's content. An array
  4439. name already acts as a pointer which points to the first element. Now it
  4440. should be clear why when during a call of SCANF, the name of the string did
  4441. not have to include the address operator &. It is already the address;
  4442.  
  4443.         char string[81];
  4444.         scanf("%s",string);
  4445.  
  4446. It was not an exception, only a short version of &string[0].
  4447.  
  4448.                                 PAGE 135
  4449.  
  4450.  
  4451. --------------------------------------------------------------------------
  4452.  
  4453. 15.2.2 STRCPY - VERSION 2.
  4454.  
  4455. String copying is an ideal application of pointers. Through the use of
  4456. pointers, the indices which had to be used during the first formulation of
  4457. STRCPY can be saved. The following construction with pointers indicates an
  4458. example;
  4459.  
  4460.         strcpy(to,from) /* version 2 */
  4461.         char *to, *from;
  4462.         {
  4463.            while((*to = *from ) != '\0')
  4464.                 {
  4465.                 to++;
  4466.                 from++;
  4467.                 }
  4468.         }
  4469.  
  4470. POINTER INCREMENTS:
  4471.  
  4472. In the STRCPY routine above, the peculiarity of the pointer becomes
  4473. obvious. If the pointer increments by one, the pointer points to the next
  4474. element. If it increments by two, if points to the element after the next.
  4475. In this strcpy version a character is transmitted from FROM to TO until the
  4476. transmission value is equal to 0. At that point the expression 
  4477. (*to = *from) has the value 0. When the expression become unequal to zero
  4478. the while loop terminates. The last transmitted character is the just
  4479. tested null byte which represents the end code of a string.
  4480.  
  4481. --------------------------------------------------------------------------
  4482.  
  4483. 15.2.3   STRCPY - VERSION 3.
  4484.  
  4485. The previous routine would not be a C program if it couldn't be shortened.
  4486. A NULL test can usually be bypassed and the incrementing of the pointers
  4487. can be squeezed into the termination conditions. Therefore the shorter
  4488. version;
  4489.  
  4490.         strcpy(from,to) /* version 3 */
  4491.         char *to,*from;
  4492.         {
  4493.            while((*to++=*from++))
  4494.                 ;
  4495.         }
  4496.  
  4497.                                 PAGE 135
  4498.  
  4499.  
  4500.  
  4501. This should be one of the shortest and fastest versions for copying strings
  4502. which could be made faster only with a special trick. More on this later.
  4503.  
  4504. To write a program which transmits FLOAT values instead of CHAR values from
  4505. one array to another, only one word must be changed in the formulation
  4506. above. That word is CHAR. In it's place the data type FLOAT is used and
  4507. immediately FLOAT values, which have a completely different construction
  4508. and require much more memory space per element, can be copied. How is this
  4509. possible ?
  4510.  
  4511. With the definition :
  4512.  
  4513.         float *to, *from;
  4514.  
  4515. the program is informed that the pointers FROM and TO are pointing to
  4516. values of data type FLOAT. This data type generally requires 4 bytes per
  4517. entry. If such a pointer is incremented by one, for example AFTER++, it
  4518. points to the following element. It is located 4 bytes from the original
  4519. element, but the compiler knows it through the definition of the pointer.
  4520. Through the incrementing of the pointer by 3, the address would change by
  4521. 12 bytes. In the data type DOUBLE, which normally uses 8 bytes, this can
  4522. also be used. For each increment of the pointer, the address is changed by
  4523. 8 bytes. a pointer is a very nice feature.
  4524.  
  4525. How does the compiler process expressions such as string[4]. when these
  4526. groups are related to each other?. Since string is the name of the array ,
  4527. which in C corresponds to the first entry (string[0]), the compiler
  4528. converts this expression into the equivalent *(string+4). First the length
  4529. of 4 elements is added to the address STRING. This makes the current
  4530. pointer point to the entry STRING[4]. Then access to this element is
  4531. accomplished through the asterisk. The parenthesis are required because the
  4532. pointer "*" has higher precedence than the addition (a table of precedence
  4533. can be found in the appendices). A comparsion between pointer and array can
  4534. be made clear with the following examples;
  4535.  
  4536.         long value, data[10];  /* defined like this */
  4537.  
  4538.         ARRAY                   THE SAME WITH POINTERS
  4539.  
  4540.         value = data[3];        value = *(data+3);
  4541.         data[10] = value;       *data = value;
  4542.         data[7]+=value;         *(data + 7) += value;
  4543.  
  4544.                                 PAGE 136
  4545.  
  4546.  
  4547.  
  4548. As shown in the program above, other operators can be used in the
  4549. construction of the *pointer. For example the *AFTER++ directive in STRCPY
  4550. indicates that the first value, to which after points (*AFTER), is obtained
  4551. and then the pointer should point to the next field(++). Can you imagine
  4552. what the following directives would do ??
  4553.  
  4554.         int i, *ip = &i;
  4555.         i = 100;
  4556.         --*ip;
  4557.  
  4558. After the definition of variable I and the INT pointer IP, which is also
  4559. initialised here, the variable I gets a value assigned. The number 100 is
  4560. stored in it. Now comes the big question, what does --*ip do?
  4561.  
  4562. First the number (100), to which ip points (*ip), is obtained. Then this
  4563. value is reduced by one, thus 100 becomes 99. This value is not stored in
  4564. variable I. The same result could have been obtained with the much sipler
  4565. expression --i.
  4566.  
  4567.                                 PAGE 137
  4568.  
  4569. --------------------------------------------------------------------------
  4570.  
  4571. 15.3 POINTER WITHOUT STORAGE.
  4572.  
  4573. During the use of pointers, you should note that they represent only a
  4574. pointer to a certain data type. The memory locations for the individual
  4575. elements must be defined separately and the pointer pointed to them.
  4576.  
  4577. The initialisation of the pointer prevents the system from giving wrong
  4578. answers or crashing. If a crash occurs when using pointers, even during the
  4579. test run of a program, first check where the pointers or the array index
  4580. are pointing.
  4581.  
  4582. A few occasional programs seem to contradict such demands;
  4583.  
  4584.         main()
  4585.         {
  4586.           char *text_ptr;
  4587.  
  4588.           text_ptr = "All point to me!";
  4589.           printf("The text is >%s<\n",text_ptr);
  4590.         }
  4591.  
  4592. Where in this program is the memory space for the string? The pointer does
  4593. nothing in this direction. It is stored somewhere in the program text, just
  4594. like in function calls (e.g. printf("Hello\n");). Also this string within
  4595. the function must be stored somewhere.
  4596.  
  4597. If the text should be changed for example with access to text_ptr the
  4598. maximum length must be observed. In the string above this is only 28
  4599. characters with one character representing the end of the string. If 30
  4600. characters are written into this space anyway a system crash can be
  4601. expected. It is possible that behind the string program code was stores
  4602. which was overwritten. Should the computer encounter such data which it
  4603. cannot understand it will go crazy.
  4604.  
  4605. The name of array symbolises the first element in the chain. Now the
  4606. question, what is expression field[3][2], if the following definition has
  4607. been used;
  4608.  
  4609.         int field[5] [5] [10];
  4610.  
  4611. Is it an element of this array? If so which one, and if not what is the
  4612. element? Examine the expression carefully. If only contains two indices but
  4613. the definition contains 3. If follows so that it cannot be an extra
  4614. element. If can only be a pointer which points to the first element. The
  4615. first element isn't field[0][0][0], but the first field to which
  4616. field[3][2] points.
  4617.  
  4618.                                 PAGE 138
  4619.  
  4620. --------------------------------------------------------------------------
  4621.  
  4622. Is it clear now what wonderful changes can result from forgetting an index?
  4623. One element of the field becomes a pointer to a field in which the missing
  4624. index is replaced with [0]. Therefore field 3 points to field [3] [0] [0].
  4625. If something like this is possible, it can be done with pointers. Later we
  4626. will see some other tricks with pointers.
  4627.  
  4628.  
  4629.                                 PAGE 139.
  4630.  
  4631. ==========================================================================
  4632.  
  4633.                          CHAPTER 16 - STORAGE CLASSES
  4634.  
  4635. This chapter discusses various groups of variables. These variables have
  4636. different lifespans during program execution. There are four storage
  4637. classes : AUTO (or LOCAL), GLOBAL, REGISTER and STATIC. Each of these
  4638. storage classes helps your program identify which C functions recognize
  4639. which variables, and determine how long the functions should use these
  4640. variables. 
  4641.  
  4642. 16.1 AUTO
  4643.  
  4644. Even though the name is unfamiliar to you, you've been using the Auto
  4645. (LOCAL) variables all along. The AUTO variables represent the default
  4646. storage class in C language.
  4647.  
  4648. These variables belong to the AUTO class because they are automatically
  4649. defined every time a function is called. On the function call, C allocates
  4650. memory space for the AUTO variables. The lifetime of an AUTO variable is
  4651. limited to the function in which the variable is declared. After the
  4652. function is abandoned through return , or the lasr brace of this function
  4653. is reached, the memory space allocated is released and can be used for
  4654. other assignments. These AUTO variables can only be used in the function
  4655. for which they were defined. The content of the variable is lost and the
  4656. name is not known to the rest of the program.
  4657.  
  4658.                                 PAGE 143
  4659.  
  4660.  
  4661. --------------------------------------------------------------------------
  4662.  
  4663. 16.2 STATIC
  4664.  
  4665. Unlike AUTO variables, STATIC variables are retained until the end of the
  4666. program and are not deleted after leaving the function. They do not have to
  4667. be created again during a new call of the function . Leaving, which means
  4668. the terminating of the executing function, should not be confused with
  4669. another function call within this function. Control may briefly pass to
  4670. another routine, but the calling routine remains active (it's waiting for a
  4671. result).
  4672.  
  4673. Here's an application of a STATIC variable. The C word static appears in
  4674. front of a definition. For example;
  4675.  
  4676.         function()
  4677.         {
  4678.            static int counter = 1;
  4679.               .............
  4680.         }
  4681.  
  4682. During the first call of the function, the variable is defined and
  4683. initialised with a starting value as in the example above. If the function
  4684. is left temporarily, a new variable isn't created during the new function
  4685. call because the variable still exists. Even it's content remains and it
  4686. does not have to be initialised again. For example, a counter in this
  4687. routine could track how many times it has been called.
  4688.  
  4689.                                 PAGE 144
  4690.  
  4691. --------------------------------------------------------------------------
  4692.  
  4693. 16.3 EXTERN
  4694.  
  4695. The next storage calls is the EXTERN or GLOBAL variable. These variables
  4696. are defined outside the function and can be used by all functions. A
  4697. section of a program would appear as follows;
  4698.  
  4699.         #define EOS '\0'
  4700.  
  4701.         int error,dummy;
  4702.  
  4703.         main()
  4704.         { ....  
  4705.         }
  4706.  
  4707. The variables which were defined can also be used by functions which are
  4708. not within the source file. The linker is given a number of files for
  4709. linking. These file contain functions which have already been compiled.
  4710. They may need GLOBAL variables which must be assigned the right values in
  4711. their program. Such variables must be declared before using them with the
  4712. EXTERN function, but they don't have to be defined:
  4713.  
  4714.         extern int error;
  4715.  
  4716. This permits the use of the variable in a file in which ERROR was not
  4717. defined.
  4718.  
  4719. Combinations such as GLOBAL STATIC variables are also permitted. Through
  4720. this definition all functions can access the GLOBAL variable within the
  4721. source file, but the situation just described of accessing this variable
  4722. with a function from another file is prohibited. The variable is only known
  4723. to the source file. Functions which first come in contact with the program
  4724. through the linker, have no access to this variable.
  4725.  
  4726.                                 PAGE 145
  4727.  
  4728. --------------------------------------------------------------------------
  4729.  
  4730. 16.4  REGISTER
  4731.  
  4732. The last storage class is REGISTER. Those of you who have some programming
  4733. experience with assemblers know what this means. A processor, the most
  4734. important part of a computer, has various internal memory locations. One
  4735. such memory segment, which should not be confused with the RAM of the
  4736. computer, is called a REGISTER. The number of registers which can be used
  4737. depends on the type of processor used. a 6502/10 used in the C64 or in the
  4738. Atari 600/800/130 has only three registers ( 2 registers and an
  4739. accumulator ). The MC68000 used in the Amiga, Atari ST and Macintosh has 17
  4740. registers. Each 68000 register is four times the size of a register in the
  4741. 6502. For this reason there are almost no compilers for 6502 computers
  4742. which offer the capability of register storage for variables. Of the 17
  4743. registers in the computer only three to five (depending on the compiler)
  4744. are made available for storage. The remaining registers are required for
  4745. internal use.
  4746.  
  4747. A variable defined as REGISTER must fit insude a register. a 68000 register
  4748. is equal to 32bits (4 bytes), which only permits integer numbers. Even if
  4749. the float value could occupy only 4 bytes it could not be stored in a
  4750. register. Valid data types are;
  4751.  
  4752.         int       char
  4753.         short     unsigned
  4754.         long
  4755.         combinations of the above
  4756.         pointers
  4757.  
  4758. Pointers are possible since they only represent the address of an object.
  4759. In the Amiga they occupy only 4 bytes.
  4760.  
  4761. There are other restrictions. The defined variable can only be an AUTO
  4762. variable since it occupies a register of the central processor. They are
  4763. rarely used and can be occupied only for a short period of time. After
  4764. leaving the function in which it was defined the register is released again
  4765. for other purposes.
  4766.  
  4767. The REGISTER variable has a speed advantage over other variables. The
  4768. program can only fully utilise this speed when these variable are used
  4769. during during many loop repetitions or calculations. The variable does not
  4770. have to be loaded from memory into a register for every use since it is
  4771. already present.
  4772.  
  4773.                                 PAGE 146
  4774.  
  4775. --------------------------------------------------------------------------
  4776.  
  4777. 16.4.1  FAST STRCPY ROUTINE.
  4778.  
  4779. Before we present the first example, we must discuss another limitation. It
  4780. isn't possible to obtain the address of a register variable with an &
  4781. operator, because a register doesn't have an address. It is not located in
  4782. RAM.
  4783.  
  4784.         strcpy(to,from) / * last version */
  4785.         register char *to, *from;
  4786.         {
  4787.              while(*to++ = *from++)
  4788.              ;
  4789.         }
  4790.  
  4791. This definition of the CHAR pointer as REGISTER should receive the maximum
  4792. speed that can be obtained in C. This could be faster only if it was
  4793. written in machine language.
  4794.  
  4795. To test the speed advantage obtainable through registers, compile the
  4796. following program. To measure the speed of the program you must use the
  4797. registers as often as possible and should not use other functions since
  4798. they only extend the time required. For this reason the program does
  4799. nothing more than count a variable down from 5,000,000 to 0.
  4800.  
  4801.         /* countdown.c 16.4.1 */
  4802.         #include <stdio.h>
  4803.  
  4804.         void main()
  4805.         {
  4806.            printf("Time comparison with and without registers\n");
  4807.            printf("RETURN for START\n");
  4808.            getchar();
  4809.            printf("%c Start without ",7);
  4810.            without_register();
  4811.            printf("%cSTOP!\nRegister routine\n",7);
  4812.            printf("RETURN for START\n");
  4813.            getchar();
  4814.            printf("%c Start With",7);
  4815.            with_register();
  4816.            printf("%cSTOP!\n\n");
  4817.  
  4818.         }
  4819.  
  4820.         with_register()
  4821.           {
  4822.             register long i=5000000; 
  4823.             while(i--)
  4824.               ;
  4825.            }
  4826.  
  4827.         without_register()
  4828.            {
  4829.              long i = 5000000;
  4830.              while(i--)
  4831.                ;
  4832.            {
  4833.  
  4834.                                 PAGE 147
  4835.                                 
  4836. --------------------------------------------------------------------------
  4837.  
  4838. The pre-processor command #include include the STDIO.H file in this C
  4839. program. This file is required because the GETCHAR routine is used to
  4840. obtain a character from the keyboard. In the Lattice C compiler, the
  4841. function is unusable because it waits for the <RETURN> key after every
  4842. character. However, it is sufficient for the program above, so it can be
  4843. used to wait for the <RETURN> key.
  4844.  
  4845. Timed by hand the author counted 51.6 seconds without register variables
  4846. and 24.1 seconds with register variables. That's impressive because it's
  4847. twice as fast when the word register is used. It should be noted that the
  4848. multi-tasking capability of the Amiga, which could have been performing a
  4849. task in the background, was not used. This would have Provided a different
  4850. result.
  4851.  
  4852.                                 PAGE 148
  4853.  
  4854. --------------------------------------------------------------------------
  4855.  
  4856. 16.5 LOCAL
  4857.  
  4858. LOCAL variables are the reverse of global variables. Different variable
  4859. groups such as REGISTER,AUTO or STATIC LOCAL can be defined. They are only
  4860. valid in the block or function in which they were created. a LOCAL variable
  4861. has precedence over a GLOBAL variable , which means that, if two variables
  4862. were defined with the same name the LOCAL variable is used. The local
  4863. variable gets preference while the GLOBAL variable disappears for the
  4864. moment. An example;
  4865.  
  4866.         /* local.c 16.5 */
  4867.         int 1 = 1;
  4868.  
  4869.         void main()
  4870.         {
  4871.            int i = 2;
  4872.            printf("%3d",i);
  4873.             {
  4874.                 printf("%3d",i);
  4875.                   {
  4876.                      int i = 3;
  4877.                      printf("%3d",i);
  4878.                    }
  4879.                  printf("%3d",i);
  4880.              }
  4881.             printf("%3d",i);
  4882.             test();
  4883.             printf("%3d",i);
  4884.         }
  4885.  
  4886.         test()
  4887.         {
  4888.            printf("%3d",i);
  4889.                {
  4890.                  int i = 4;
  4891.                  printf("%3d",i);
  4892.                 }
  4893.         }
  4894.  
  4895. The numbers 2,2,3,2,2,1 and 4 are displayed sequentially. In the MAIN
  4896. function a new local variable is declared so that the GLOBAL variable i is
  4897. no longer addressable. The following blocks keeps this configuration and
  4898. another 2 appears. Then another block follows in which another i variable
  4899. is defined. Because of this, the previous block becomes invisible to the
  4900. program and the current one prevails. The result of the output is 3. After
  4901. the program leaves all blocks, the hidden variable appears again. The
  4902. previous variable with the value 3 is erased by leaving this block then
  4903. disappears. The test function is now called and proceeds to output i. Since
  4904. no LOCAL variable is known as this point, the output of the GLOBAL
  4905. variable, which is 1, is used. Finally a LOCAL integer variable is
  4906. activated which overshadows the global variable again. This ensures that
  4907. the last variable defined in a block is used, and that often used name
  4908. (i,x or j etc..) are recognised as runtime variables in many loop with
  4909. different values.
  4910.  
  4911.                                 PAGE 150
  4912.  
  4913. --------------------------------------------------------------------------
  4914.  
  4915.                      CHAPTER 17 - USER DEFINED LIBRARIES.
  4916.  
  4917. One advantage of the programming in C is the modular construction of
  4918. programs, which can accept existing functions used in other programs. The
  4919. #include directive lets you add external files that have frequently used
  4920. functions to the current program before compiling. The compiler processes
  4921. one large file instead of several small files.
  4922.  
  4923. Every C programmer writes his own functions at some time or another. You've
  4924. already entered two functions  (STRLEN and STRCPY); let's use these. Most
  4925. compilers contain these functions. However, viewing them can give us an
  4926. understanding of how user written functions work.
  4927.  
  4928. Save these functions to your own file under the name STRING.C. You can
  4929. include these functions in your own program using the #include directive.
  4930. The following line searched the main directory for the INCLUDE file
  4931. STRING.C
  4932.  
  4933.         #include "string.c"
  4934.  
  4935. The following line also adds the STRING.C file to the main file;
  4936.  
  4937.         #include <string.c>
  4938.  
  4939. Of the two syntaxes, the second line is much more flexible than the first
  4940. since it searches many different directories for the same file.
  4941.  
  4942. Most C implementations have INCLUDE files as standard equipment. Files with
  4943. .h extensions contain mostly #define directives. You can find these
  4944. functions in a file such as AMIGA.LIB or LC.LIB. Include files can be
  4945. included on demand. The syntax reads;
  4946.  
  4947.         #include <file.h>
  4948.  
  4949. Before starting with INCLUDE, first you need something that can be
  4950. included. A useful function can be written to compare strings. Since
  4951. strings are not elementary data types they cannot be compared with;
  4952.  
  4953.          if(string1 == string2) /* this is wrong ! */
  4954.  
  4955. If you wrote the variables string1 and string2 as character arrays, the
  4956. name would correspond to the address of the first element (&string1[0]).
  4957. Therefore the addresses of the two arrays always differ. Since both arrays
  4958. have been assigned by the compiler to separate memory locations for their
  4959. char entries the comparison is completely useless. The only case
  4960. (theoretically) in which this IF test can be fulfilled is if one or the
  4961. other variable was defined as a pointer and if the pointer pointed to the
  4962. same string. This method doesn't work.
  4963.  
  4964.                                 PAGE 153        
  4965.  
  4966. --------------------------------------------------------------------------
  4967.  
  4968. 17.1 THE STRCMP FUNCTION.
  4969.  
  4970. You now have to write a program to compare each element of the first string
  4971. one at a time with each element of the second string:
  4972.  
  4973.         strcmp(s,t)
  4974.         register char *s, *t;
  4975.         {
  4976.            while(*s==*t)
  4977.               {
  4978.               if (!*s)
  4979.               return(0); /* end reached (*s==0) */
  4980.               s++;
  4981.               t++;
  4982.               }
  4983.            return(*s - *t);
  4984.         }
  4985.  
  4986. The STRCMP function compares the characters of the S string with those of
  4987. the T string. As long as the characters are equal (*s==*t), the WHILE loop
  4988. executes. A test determines whether the last character matches the \0
  4989. marker EOS (end of string). If so, both strings must be identical, since S
  4990. and T end with EOS. Otherwise the pointers move to the next element and the
  4991. process repeats. 
  4992.  
  4993. If a character appears within S which differs from the T character, the
  4994. WHILE loop terminates and the difference between the two characters (*s -
  4995. *t) returns to the calling program. Negative values indicate that the S
  4996. string was smaller than T. Positive values mean the opposite. A null
  4997. returned after the IF test indicates that both strings are completely
  4998. identical.
  4999.  
  5000. Store this function and the other two files below as STRINGFUNC.C. Since
  5001. the older STRLEN routine could be improved, we will use pointers this time.
  5002. Instead of the indices, the pointer moves over all entries of the string up
  5003. to the EOS character. The start value must be stored first so that the
  5004. number of increments can be computed. That is faster than counting with an
  5005. additional variable. The STRINGFUNC.C file therefore appears as follows:
  5006.  
  5007.         /* stringfunc.c 17.1 */
  5008.  
  5009.         strcpy(to, from)
  5010.         register char *to,*from;
  5011.         {
  5012.            while(*to++ = *from++)
  5013.            ;
  5014.          }
  5015.  
  5016.                                 PAGE 154
  5017.  
  5018. --------------------------------------------------------------------------
  5019.  
  5020.         strlen(s) /* Conversion to pointer */
  5021.         register char *s;
  5022.         {
  5023.            register char *help = s; /* store initial position */
  5024.            while(*s)
  5025.             s++;
  5026.            return (s-help);
  5027.            /* difference between pointers is element number */
  5028.         }
  5029.  
  5030.  
  5031.         strcmp(s,t)
  5032.         register char *s, *t;
  5033.         {
  5034.            while(*s==*t)
  5035.            {
  5036.               if(!*s)
  5037.               return(0); /* end reached (*s==0) */
  5038.               s++;
  5039.               t++;
  5040.            }
  5041.            return(*s - *t); /* difference between two strings */
  5042.         }
  5043.  
  5044. Now let's see if they function properly. For this you'll use two strings
  5045. which are initialised in the program.
  5046.  
  5047.         /* stringtest.c 17.2 */
  5048.  
  5049.         #include "stringfunc.c"
  5050.  
  5051.         /* global arrays can be initialised ! */
  5052.  
  5053.         char string1[] = "hello!";
  5054.         char string2[7] = {'h','e','l','l','o','!',0};
  5055.  
  5056.         main()
  5057.         {
  5058.            printf("\nComparison of >%s< and >%s< is%d\n",string1,string2,
  5059.                  strcmp(string1,string2));
  5060.            printf("Now >%s< and >%s< result in %d\n\n",string1,"huhu!",
  5061.                  strcmp(string1,"huhu!"));
  5062.         }
  5063.  
  5064. First we will look at the expected results of the function call STRCMP. The
  5065. first call returns 0 since both strings are equal. The second function call
  5066. returns -16. This number is the result of the comparison of the E and U
  5067. characters. This means that the first different character in the string
  5068. ("hello!") is smaller than the first different character in the second
  5069. string ("huhu!").
  5070.  
  5071. Array initialisation is new to this program. Until now each element was
  5072. stored idividually. Automatic variables wouldn't allow storage in any other
  5073. form. With GLOBAL variables, a string can be initialised directly or as in
  5074. the second example, every character is initialised separately.
  5075.  
  5076.                                 PAGE 155
  5077.  
  5078. --------------------------------------------------------------------------
  5079.  
  5080. In the first example there wasn't even an indication of how many elements
  5081. string1[] should have. This is another indication that the C language was
  5082. intended for those who consider laziness a virtue. The compiler must
  5083. determine the number of the character on it's own. It initialises string1
  5084. with 7 elements (don'f forget the null byte at the end.). Those who prefer
  5085. can indicate the value as in the second example.
  5086.  
  5087. If you assign elements individually (example 2) to the fields they must be
  5088. contained in braces and separated by commas. For multiple dimensions,
  5089. multiple braces must be used.
  5090.  
  5091.         int field[4][4] =
  5092.         {
  5093.         { 1, 2, 3, 4 } ,
  5094.         ( 6, 3, 4, 9 } ,
  5095.         { 3, 4, 5, 6 } ,
  5096.         {12, 9, 0, 2 } ,
  5097.         };
  5098.  
  5099. This formulation assigns field [4][4] the proper values where the first
  5100. values {1, 2, 3, 4} are stored in the fields FIELd[0][0] to FIELD[0][3].
  5101. The inner braces are not required on some compilers and the directive could
  5102. appear as follows:
  5103.  
  5104.         int field[4][4] = {1,2,3,4,6,3,4,9,3,4,5,6,12,9,0,2};
  5105.  
  5106. When some elements are not initialised, they don't have to be listed. All
  5107. elements left out are automatically assigned a null.
  5108.  
  5109.         int field[3][3] = 
  5110.         {
  5111.           {3, 2},
  5112.           {4},
  5113.           {3, 4, 5},
  5114.         };
  5115.  
  5116. The fields FIELD[0][2], field[1][1] and field[1][2] contain nulls. A
  5117. semicolon must follow the definition. After the inner braces and the last
  5118. brace there must be commas. Remember that initialisation only affects
  5119. GLOBAL or STATIC variables and not AUTO variables.
  5120.  
  5121.                                 PAGE 156
  5122.  
  5123. --------------------------------------------------------------------------
  5124.  
  5125. 17.2 ITOA
  5126.  
  5127. Another routine seen frequently in connection with strings is ITOA (Integer
  5128. to ASCII). It converts an integer value into the corresponding character
  5129. string. When you pass the number 123 ITOA returns the string "123" in a
  5130. character array. This is very important when preparing text that contains
  5131. numbers. All convewrsions usually preformed by PRINTF can also be done with
  5132. user functions.
  5133.  
  5134. The ITOA function requires, as parameters, an integer value which it can
  5135. convert and, and a string to store the result. The head of the function
  5136. definition reads as follows;
  5137.  
  5138.         itoa(n, s)
  5139.         char s[];
  5140.         int n;
  5141.  
  5142. The modulo operator % performs the conversion. By dividing the number by 10
  5143. you obtain the last place. Then the code for the number '0' is added to get
  5144. the first character. The number is then divided by 10 to shift it left one
  5145. space and the last number drops off. The same procedure is performed on the
  5146. new last position. The program section for this process appears as follows,
  5147. if the index for the character array is called I;
  5148.  
  5149.         do
  5150.            s[i++] = n % 10 + '0';
  5151.         while ((n/=10) > 0);
  5152.  
  5153. The last place is converted and stored in S until the number which was
  5154. stored in N has reached 0 through constant division. The sign should not be
  5155. forgotten since it could cause problems for the loop (number larger than
  5156. 0). The simplest process makes the number positive before the conversion and ,
  5157. if necessary, sets a flag for a negative value. After the completed
  5158. conversion , the string returns the minus sign.
  5159.  
  5160. The completed processing converts the number 123 into the string "321", but
  5161. only the last place is processed and stored in the string. The solution to
  5162. this problem is very simple. Write another function that reverses the
  5163. string. Assuming that such a function already exists (see the next section
  5164. for the function) the routine would appear as follows:
  5165.  
  5166.                                 PAGE 137
  5167.                                 
  5168.  
  5169. --------------------------------------------------------------------------
  5170.  
  5171.         /**********************************/
  5172.         /* Name : itoa                    */
  5173.         /* Parameter: n(int), s(string)   */
  5174.         /* Function: Convert int to string*/
  5175.         /* Comment :Requires Reverse()    */
  5176.         /**********************************/
  5177.  
  5178.         #define EOS '0'
  5179.         #define FALSE 0
  5180.         #define TRUE 1
  5181.  
  5182.         itoa(n, s)
  5183.         register int n;
  5184.         register char *s;
  5185.         {
  5186.             register int i=0;
  5187.             register int sign = FALSE;
  5188.  
  5189.             if(n < 0)
  5190.               {
  5191.                 sign = TRUE;
  5192.                 n = -n;
  5193.               }
  5194.             do
  5195.               s[i++] = n % 10 + '0';
  5196.             while( n/=10);
  5197.             if(sign)
  5198.                s[i++] = '-';
  5199.             s[i] = EOS;
  5200.             reverse(s);
  5201.         }
  5202.  
  5203. The large header contains important information. The function developed by
  5204. the user should be ready for use when it is finished. After some time the
  5205. function name and the parameters to be passed may have been forgotten. At
  5206. that time you could consult the header with it's comments. The function can
  5207. be compiled independant of other functions. If the compiler permits it, it
  5208. can be stored in a library. Of course the source files can be included into
  5209. the current file with:
  5210.  
  5211.         #include "itoa.c"
  5212.  
  5213. This increases compiler time, of course.
  5214.  
  5215. Since this function should be accepted in the library, it should be the
  5216. latest state-of-art. This can be done with the ITOA function by defining
  5217. all variables as REGISTER variables. The define required for this function
  5218. sshould not be omitted, even it appears somewhat cumbersome to determine a
  5219. define for a single application. It improves readability since larger
  5220. programs usually access these macros.
  5221.  
  5222.                                 PAGE 158
  5223.  
  5224. --------------------------------------------------------------------------
  5225.  
  5226. 17.3  REVERSE.
  5227.  
  5228. Now to the REVERSE function which can reverse a string passed to it.
  5229. Construction of the routine doesn't present a problem. Two pointers, or
  5230. indices, are needed for the beginning and end of the string. These pointers
  5231. exchange their elements between themselves and are then moved toward each
  5232. other. The pointer at the beginning is incremented and the one at the end
  5233. is decremented. Exchange continues until the two pointers are equal, i.e.,
  5234. point to the same element. The routine is presented complete with a
  5235. commented header.
  5236.  
  5237.         /***********************************/
  5238.         /* Name: Reverse                   */
  5239.         /* Parameter: s(string)            */
  5240.         /* Function: Reverse string        */
  5241.         /* Comment : Requires STRLEN()     */
  5242.         /***********************************/
  5243.  
  5244.         reverse(s)
  5245.         register char *s;
  5246.         {
  5247.             register int c, i, j;
  5248.  
  5249.         for (i=0, j=strlen(s) - 1; i<j; i++,j--)
  5250.             {
  5251.                 c   = s[i];
  5252.                 s[i]=s[j];
  5253.                 s[j]=c;
  5254.             }
  5255.         }
  5256.  
  5257. The STRLEN function initialises the index J, which sould point to the last
  5258. element of S. Every C compiler pachake has STRLEN included in one of it's
  5259. libraries, or you can use the STRLEN function defined in the previous
  5260. chapter. Both routine (ITOA and REVERSE) should be stored in the library
  5261. labelled ITOA.C since it will be accessed later. Please note that the ITOA
  5262. routine also comes as standard equipment with most C compilers. These
  5263. standard everyday functions have already been written by others.
  5264.  
  5265.                                 PAGE 159
  5266.  
  5267. --------------------------------------------------------------------------
  5268.  
  5269.                                 CHAPTER 18 C. FEATURES.
  5270.  
  5271. We have mentioned many times that the C language is much more flexible than
  5272. any other languages. C has many features that Basic doesnt, and is still
  5273. much simpler to use than assembly language.
  5274.  
  5275. This chapter examines some components of C which arent possible in other
  5276. languages. These components are partly responsible for for allowing the
  5277. user to take full advantage of C's speed and flexibility.
  5278.  
  5279.  
  5280. 18.1 THE ? : OPERATOR.
  5281.  
  5282. The ?: conditional operator evaluates the the first statement and returns,
  5283. if the expression was true, the statement which follows. If the expression
  5284. was false (=), the operator returns the second statement following the
  5285. colon. This operator uses the syntax :
  5286.  
  5287.         result = (expression1) ? (expression2) : (expression3);
  5288.  
  5289. If expression1 is unequal to zero, expression2 becomes the result.
  5290. Otherwise expression3 is returned. A concrete example :
  5291.         
  5292.         c = (a>b) ? a : b;
  5293.  
  5294. This would be similar to the if construction:
  5295.  
  5296.         if(a>b)
  5297.           c = a;
  5298.         else
  5299.           c = b;
  5300.  
  5301. This term delivers the maximum of a and b. Since this is simple to
  5302. formulate, this operation usually determines minimum and maximum quantity.
  5303. The define :
  5304.  
  5305.         #define MIN(a,b)        (((a)<(b))?(a):(b))
  5306.         #define MAX(a,b)        (((a)>(b))?(a):(b))
  5307.  
  5308. Take a look at STDIO.H which youll find with your compiler. There youll
  5309. find the definition.
  5310.  
  5311.                                 PAGE 163
  5312.  
  5313. ------------------------------------------------------------------------
  5314.  
  5315. 18.2 THE SIZEOF FUNCTION.
  5316.  
  5317. The SIZEOF (size of) function returns the sizes of objects (variables)
  5318. regardless of type. The unit returned by this operator is defined on the
  5319. basis of CHAR elements. The following example followed by SIZEOF(character)
  5320. returns 1:
  5321.  
  5322.         char character = 'a';
  5323.  
  5324. The result is always the number of occupies bytes for the object under
  5325. investigation. The following short program determines how much memory is
  5326. used by the various data types in your compiler. This will tell you if an
  5327. INT variable occupies 2 bytes (most C compilers) or 4 bytes (Lattice).
  5328.  
  5329.         /* sizeof 18.2 */
  5330.         main() /* inidicates memory requirement for data types*/
  5331.         {
  5332.            printf("\nData type\tMemory in bytes\n");
  5333.            printf("char\t\t&d\n",sizeof(char));
  5334.            printf("short\t\t%d\n",sizeof(short));
  5335.            printf("int\t\t%d\n",sizeof(int));
  5336.            printf("long\t\t%d\n",sizeof(long));
  5337.            printf("float\t\t%d\n",sizeof(float));
  5338.            printf("double\t\t%d\n",sizeof(double));
  5339.            printf("pointer\t\t%d\n",sizeof(* char));
  5340.         }
  5341.  
  5342.                                 PAGE 164
  5343.  
  5344. ---------------------------------------------------------------------------
  5345.  
  5346. 18.3 BIT MANIPULATION.
  5347.  
  5348. This section describes the remaining operators, which deal with controlling
  5349. individual bits.
  5350.  
  5351. Operators for bit manipulations exist in addition to the logical
  5352. combinations. A bit (binary digit) represents a position in a binary number
  5353. and can therefore only assume one of two values (0 and 1). The conversion
  5354. into the binary system is similar to the conversion into the octal or
  5355. hexadecimal system. The bit is also the smallest unit which the computer
  5356. can use. It acts as the basis for all other nunbers which can be used in
  5357. the computer. For example, a byte consists of 8 bits, a word of 16bits and
  5358. a long word of 32 bits. A character may be stored in a CHAR variable.
  5359. Characters are stored in bytes; a byte can accept 256 different kinds of
  5360. numbers. Depending on the compiler, an integer value contains 16 or 32 bits
  5361. and a long value 32 bits. Individual bits of these data types can also be
  5362. accessed. These operators cannot be used with FLOAT or DOUBLE variables.
  5363.  
  5364.  
  5365. 18.3.1 THE "AND" COMMAND.
  5366.  
  5367. The AND operator consists of the & character. Maybe you thought this is the
  5368. address operator. This character can be used for both purposes but it's
  5369. hard to explain why this is so. You must know the context in which it is
  5370. used. If is is placed alone in front of a variable, it represents the
  5371. address operator. If it is placed between two values in a normal arithmetic
  5372. equation, then it is the binary AND.
  5373.  
  5374. The concepts logical and binary help you distinguish between the two
  5375. completely different operators. The logical and is different from &&.
  5376.  
  5377. With AND (&) individual bits can be reset. A set bit has the value 1, a
  5378. reset bit the value 0. The following table shows the connection between
  5379. various bit combinations.
  5380.  
  5381.         AND             OR              EXOR
  5382.         ------------------------------------
  5383.           &             |               ^
  5384.         0   0   0       0   0   1       0   0   1 
  5385.         1   0   1       1   1   1       1   1   0
  5386.  
  5387.                                 PAGE 165
  5388.                                 
  5389. ---------------------------------------------------------------------------
  5390.  
  5391.  
  5392. According to the AND a bit is set (1) when both bits are set, otherwise the
  5393. result is a zero. This is comparable with :
  5394.  
  5395.         if(bit1 == 1 && bit2 ==1)
  5396.            result_bit = 1;
  5397.         else
  5398.            result_bit = 0;
  5399.  
  5400.  
  5401. 18.3.2 THE "OR" OPERATOR.
  5402.  
  5403. With the (|) OR operator bits can be set. A glance at the table above will
  5404. help you understand the various combinations of bits. In OR the resulting
  5405. bit is set if one or both bits are set. Only if both bits are 0 is the
  5406. result or OR also 0. The | sets individual bits and the & resets the bits.
  5407.  
  5408. A mask acts as a storage area for the bits. A mask is represented by a
  5409. number placed over the value to be processed. If a variable is ORed with
  5410. this mask, all bits set in the mask are now also set in the variable.
  5411.  
  5412. EXAMPLE :
  5413.  
  5414. Bit number 2 should be set in the variable FLAGS (the count starts at
  5415. zero).:
  5416.  
  5417.         #define MASK 4
  5418.         int flags = 73;
  5419.  
  5420.         flags |= MASK;
  5421.  
  5422. After this operation, the OR with the value 2**2 (number of the bit to be
  5423. set) = 4 (sets the second bit in the variable FLAGS).
  5424.  
  5425. A targeted resetting of certain bits sets the corresponding bits of the
  5426. mask to 0. With the AND operation the desired zero bits are obtained.
  5427. Example: bits 1 and 4 should be reset.
  5428.  
  5429.         int flags = 37;
  5430.         flags &= 0355; /* All bits expect 1 and 4 are set (0-7) */
  5431.  
  5432. Every bit has its own value according to priority. For example bit 3 has a
  5433. value of 8 (2**3). The table below shows the individual bit values:
  5434.  
  5435. bit nunber   0    1    2    3    4    5    6    7 
  5436. Value        1    2    4    8   16   32   64  128
  5437.  
  5438. Some examples for bit operations:
  5439.  
  5440.         1 & 2 = 0
  5441.         2 & 6 = 2
  5442.         7 & 8 = 0
  5443.         9 & 12= 8
  5444.  
  5445.                                 PAGE 166
  5446.  
  5447. ----------------------------------------------------------------------------
  5448.  
  5449.  
  5450. The last example should be examined closer in the binary system.
  5451.  
  5452. 9(dec) = 1001 (binary), 12 (dec) = 1100 (binary)
  5453.  
  5454.         1001
  5455.         &   1100
  5456.         --------
  5457.             1000(binary) = 8 (decimal)
  5458.  
  5459. The same operation for OR:
  5460.  
  5461.         1 | 2 = 3
  5462.         2 | 6 = 6
  5463.         7 | 8 = 15
  5464.         9 | 12= 13
  5465.  
  5466. The last line expressed in binary:
  5467.  
  5468.         1001
  5469.         1100
  5470.         ----
  5471.         1101
  5472.  
  5473.         1101 (binary) = 13 (decimal)
  5474.  
  5475. It is important that the characters & and && are kept separate from each
  5476. other. & connects expressions bit by bit. && also makes a logical
  5477. comparison from which either a 1 (true) or 0 (false) is returned. Therefore
  5478. 2 & 1 = 0 but 2 && 1 = 1.
  5479.  
  5480. There is also a distinction between the operators | and ||. Loops and
  5481. conditions may result in strange behaviour if you confuse these operators.
  5482.  
  5483.  
  5484. 18.3.3 BITWISE SHIFT OPERATORS.
  5485.  
  5486. >>  <<
  5487.  
  5488. Operators for bit shifting are >> and <<. They permit bit shifting to the
  5489. left or right within a field. A shift to the left (<<) by one position is
  5490. the same as multiplying by 2, only it is much faster. All of this is
  5491. dependant on how data and numbers are stored and processed in the computer.
  5492. A shift to the right equals a division by 2. Depending on the data type,
  5493. either zero bits or set bits move into free locations. For unsigned values,
  5494. zero bits are shifted in every case. For normal signed INT values it
  5495. depends on the compiler used. For positive numbers, zero bits should be
  5496. added to the left, and for negative numbers one bit. This is compiler
  5497. dependant and there is no guarantee of how this works.
  5498.  
  5499.                                 PAGE 167
  5500.  
  5501. ----------------------------------------------------------------------------
  5502.  
  5503.  
  5504. The number of shifts is indicated behind the operator.
  5505.  
  5506.         5 << 3 = 40
  5507.  
  5508. 101 (binary) shifted left by 3 bits (zero bits are shifted in): 101000
  5509. (binary) = 40 (decimal).
  5510.  
  5511. Use the program in the previous section for converting decimal numbers into
  5512. binary numbers.
  5513.  
  5514.  
  5515. 18.3.4 EXCLUSIVE OR
  5516.  
  5517. The EXCLUSIVE OR operator ^ is related, as the name indicates, to the OR
  5518. operator. The only difference lies in the fact that both bits are set. The
  5519. OR operation results in a set bit, but the EXCLUSIVE OR resets a bit. The
  5520. table for EXCLUSIVE OR is as follows:
  5521.  
  5522.         EXOR    0     1
  5523.         ---------------
  5524.         0       0     1
  5525.         1       1     0
  5526.  
  5527. for example 2 ^ 1 = 3
  5528.  
  5529. Please do not confuse ^ with the up arrow for exponentiation. This does not
  5530. exist in the C language.
  5531.  
  5532. REMEMBER : The bit is set only if both bits are different.
  5533.  
  5534.  
  5535. 18.3.5 ONE'S COMPLEMENT.
  5536.  
  5537. The one's complement operator ~ requires only one parameter. All bits of
  5538. the parameter are reversed. Set bits are unset and vice versa. It is
  5539. recommended to use this operator only for variable which were defined as
  5540. unsigned, or the sign is also affected.
  5541.  
  5542.         unsigned number = ~3;
  5543.  
  5544. In the variable all bits except the first two are set (priority 0 and 1 = 1
  5545. + 2 = 3) so that the variable now recieves the following bit sequence
  5546. (starting from a 16-bit integer):
  5547.  
  5548.         1111 1111 1111 1100
  5549.         = 65532
  5550.  
  5551.                                 PAGE 168
  5552.  
  5553. -----------------------------------------------------------------------------
  5554.  
  5555.  
  5556. 18.4 GOTO
  5557.  
  5558. Perhaps GOTO sounds familiar from BASIC, but the C implementation is a true
  5559. curiosity. This statement has a bad reputation in C, since it can destroy a
  5560. well structured program. Jumping in a function can defeat the purpose of
  5561. clarity in programming. Nevertheless the GOTO statement is not totally
  5562. useless. It can be used effectively in error trapping. If an error occurs
  5563. within several loops, which makes progress impossible, only the GOTO
  5564. statement offers escape. The usual break directive can only stop one loop,
  5565. not several at once. Some tests and other break commands could also
  5566. terminate all loops. It is preferable to use GOTO.
  5567.  
  5568.  
  5569. The use of the GOTO statement of course assumes a label (a marked line to
  5570. which the jump should be made).
  5571.         
  5572.         label: printf("This is where goto will Jump!\n");
  5573.                . . . . . . .
  5574.                if(error)
  5575.                   goto label;
  5576.  
  5577. The labels can be defined in the program text anywhere, but must include a
  5578. colon. They are only required for the GOTO statement and are formed exactly
  5579. like variable names.
  5580.  
  5581. NOTE : The label and jump commands must be used in the same function. It is
  5582. not possible to jump across functions.
  5583.  
  5584.  
  5585.                                 PAGE 169
  5586.  
  5587. ----------------------------------------------------------------------------
  5588.  
  5589. See document part 2! 
  5590.  
  5591. ----------------------------------------------------------------------------
  5592.  
  5593.  
  5594.            This File was Downloaded from ....... > T H E  J A M < <
  5595.  
  5596.  
  5597.            Running on A3000 (One Parted +2 Node's)
  5598.  
  5599.            Node 1 : 49(0)201-626-047      Node 2 : 49(0)201-622-897
  5600.  
  5601.            System-Operator : Selim and Rudi       Co-Operator : Oli
  5602.  
  5603.  
  5604.  
  5605.                             This file passed through
  5606.                                      __        __     __ __
  5607.                      |/\ |/\  /||_ ||  ||/\   |  | /||  || \
  5608.                      |\/ |\/ |-| |_||-| |\/   | __|-|   ||-
  5609.                      |   | \ | | __||__|| \   |__|| |  / |_/
  5610.  
  5611.  
  5612.            L S D   U N I T E D   S T A T E S   H E A D Q U A R T E R S
  5613.  
  5614.                                  (501) 336-9661
  5615.  
  5616.                          long before you ever got it... 
  5617.  
  5618.  
  5619.